0

I am trying to know if an IP address is reachable using the code below. But every time I am getting "Not Reachable" even though the machine is running. I have tried using several alive IPs but I'm always getting "Not Reachable". Please help.

public class CheckIP {
public static void main(String args[]) throws UnknownHostException, IOException{
    String ip = "78.46.84.171";

    if(InetAddress.getByName(ip).isReachable(100)){
        System.out.println("Reachable.");
    }
    else{
        System.out.println("Not Reachable.");
    }
}
}
user207421
  • 305,947
  • 44
  • 307
  • 483
1fuyouinfinite
  • 1
  • 1
  • 1
  • 14

1 Answers1

1

Can you ping the machine from the command line? E.g. ping 78.46.84.171?

According to the oracle docs:

Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. 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.

The timeout value, in milliseconds, indicates the maximum amount of time the try should take. If the operation times out before getting an answer, the host is deemed unreachable. A negative value will result in an IllegalArgumentException being thrown.

To summarize the possbile errors:

  • Is a firewall blocking ICMP requests? (see above ping command)
  • Maybe your timeout with 100 ms is to short (try to increase to, e.g. 1000)
  • Are you using Linux / Mac? Maybe you lack the privilege to do pings, so the isReachable(int) implementation tries a TCP-Connect but fails. (try a windows machine or execute your program as root or via sudo)
bratkartoffel
  • 1,127
  • 1
  • 13
  • 37
  • Note the 'if privilege can be obtained'. Typically it can't. And the Windows imp,emendation doesn't use ICMP. So the typical implementation really uses TCP port 7. – user207421 Jun 03 '15 at 06:02