How to ping an IP address

Mehdi picture Mehdi · Jul 16, 2012 · Viewed 250.1k times · Source

I am using this part of code to ping an ip address in java but only pinging localhost is successful and for the other hosts the program says the host is unreachable. I disabled my firewall but still having this problem

public static void main(String[] args) throws UnknownHostException, IOException {
    String ipAddress = "127.0.0.1";
    InetAddress inet = InetAddress.getByName(ipAddress);

    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");

    ipAddress = "173.194.32.38";
    inet = InetAddress.getByName(ipAddress);

    System.out.println("Sending Ping Request to " + ipAddress);
    System.out.println(inet.isReachable(5000) ? "Host is reachable" : "Host is NOT reachable");
}

The output is:

Sending Ping Request to 127.0.0.1
Host is reachable
Sending Ping Request to 173.194.32.38
Host is NOT reachable

Answer

Arvik picture Arvik · Jul 16, 2012

InetAddress.isReachable() according to javadoc:

".. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host..".

Option #1 (ICMP) usually requires administrative (root) rights.