Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with isReachable in InetAddress class

As an assignment I have to find all the alive computers on a LAN. For which I am using isReachable function of InetAddress class. But problem is that nothing is shown reachable to me. So I tried to have isReachable with Google's IP but still this is unreachable.

Here is the code:

import java.net.*;

public class alive{
    public static void main(String args[]){
        try{
            InetAddress ia = InetAddress.getByAddress(new byte[]{(byte)209, (byte)85, (byte)153, (byte)104});
            boolean b = ia.isReachable(10000);
            if(b){
                System.out.println("Reachable");
            }
            else{
                System.out.println("Unrachable");
            }

        }catch(Exception e){
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output is : Unreachable

like image 650
codeomnitrix Avatar asked Jan 24 '11 06:01

codeomnitrix


2 Answers

Here are some details on why isReachable() might not always work as expected

  1. http://bordet.blogspot.com/2006/07/icmp-and-inetaddressisreachable.html
  2. http://www.coderanch.com/t/206934/sockets/java/InetAdress-isReachable-Ping-Permissions

The correct way for you is to use the ICMP protocol. This is what ping uses internatlly, I believe. Here is an example that get you started.

like image 95
Aravind Yarram Avatar answered Oct 25 '22 00:10

Aravind Yarram


Here is the code which is platform independent, but requires information about any open port on the other machine (which we have most of the time).

private static boolean isReachable(String addr, int openPort, int timeOutMillis) {
    // Any Open port on other machine
    // openPort =  22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
    try {
        try (Socket soc = new Socket()) {
            soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
        }
        return true;
    } catch (IOException ex) {
        return false;
    }
}
like image 20
Sourabh Bhat Avatar answered Oct 24 '22 22:10

Sourabh Bhat