Search code examples
javapinghost

How to ping an IP address


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


Solution

  • You can not simply ping in Java as it relies on ICMP, which is sadly not supported in Java

    http://mindprod.com/jgloss/ping.html

    Use sockets instead

    Hope it helps