Open In App

Pinging an IP address in Java | Set 1

Improve
Improve
Like Article
Like
Save
Share
Report

PING stands for Packet InterNet Groper in computer networking field. It’s a computer network administration software used to test the reachability of a host on an Internet Protocol (IP) network. It measures the round-trip time for messages sent from the originating host to a destination computer that are echoed back to the source.

Ping operates by sending Internet Control Message Protocol (ICMP/ICMP6 ) Echo Request packets to the target host and waiting for an ICMP Echo Reply. The program reports errors, packet loss, and a statistical summary of the results.

Internet Control Message Protocol (ICMP) : The Internet Control Message Protocol (ICMP) supports protocol in the Internet Protocol suite. It is used by network devices like routers, to send error messages and operational information indicating whether a request to service is available or not or that a host or router could not be reached.
ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems.
ICMP is not supported in Java and ping in Java as it relies on ICMP
We can’t simply ping in Java as it relies on ICMP, which is sadly not supported in Java

This Java Program pings an IP address in Java using InetAddress class. It is successful in case of Local Host but for other hosts this program shows that the host is unreachable.




// Java Program to Ping an IP address
import java.io.*;
import java.net.*;
  
class NewClass
{
  // Sends ping request to a provided IP address
  public static void sendPingRequest(String ipAddress)
              throws UnknownHostException, IOException
  {
    InetAddress geek = InetAddress.getByName(ipAddress);
    System.out.println("Sending Ping Request to " + ipAddress);
    if (geek.isReachable(5000))
      System.out.println("Host is reachable");
    else
      System.out.println("Sorry ! We can't reach to this host");
  }
  
  // Driver code
  public static void main(String[] args)
          throws UnknownHostException, IOException
  {
    String ipAddress = "127.0.0.1";
    sendPingRequest(ipAddress);
  
    ipAddress = "133.192.31.42";
    sendPingRequest(ipAddress);
  
    ipAddress = "145.154.42.58";
    sendPingRequest(ipAddress);
  }
}


Output :

Sending Ping Request to  127.0.0.1
Host is reachable
Sending Ping Request to  133.192.31.42
Sorry! We can't reach to this host
Sending Ping Request to  145.154.42.58
Sorry! We can't reach to this host

Next : Pinging an IP address in Java | Set 2 (By creating sub-process)

Definition Source :
https://en.wikipedia.org/wiki/Internet_Control_Message_Protocol
https://en.wikipedia.org/wiki/Ping_(networking_utility)



Last Updated : 29 Jun, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads