Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List devices on local network with ping

I'm trying to create a function that lists all connected devices on a local network. What I do is to ping any address from addresspace x.x.x.0 to x.x.x.255, but it doesn't seem to work properly. Could anyone explain or extend my code somehow? I do get a response from the phone (10.0.0.17) and a default gateway (10.0.0.138). The latter shouldn't even be there (matter of fact I don't know what a default gateway is but ignore that). I am missing the IP from this computer though.

public ArrayList<InetAddress> getConnectedDevices(String YourPhoneIPAddress) {
    ArrayList<InetAddress> ret = new ArrayList<InetAddress>();

    LoopCurrentIP = 0;

    //        String IPAddress = "";
    String[] myIPArray = YourPhoneIPAddress.split("\\.");
    InetAddress currentPingAddr;

    for (int i = 0; i <= 255; i++) {
        try {

            // build the next IP address
            currentPingAddr = InetAddress.getByName(myIPArray[0] + "." +
                    myIPArray[1] + "." +
                    myIPArray[2] + "." +
                    Integer.toString(LoopCurrentIP));

            // 50ms Timeout for the "ping"
            if (currentPingAddr.isReachable(50)) {
                if(currentPingAddr.getHostAddress() != YourPhoneIPAddress){
                    ret.add(currentPingAddr);

                }
            }
        } catch (UnknownHostException ex) {
        } catch (IOException ex) {
        }

        LoopCurrentIP++;
    }
    return ret;
}
like image 289
rtc11 Avatar asked Sep 14 '12 16:09

rtc11


1 Answers

Here's slightly modified loop which should do the trick (or worked for me at least);

try {
    NetworkInterface iFace = NetworkInterface
            .getByInetAddress(InetAddress.getByName(YourIPAddress));

    for (int i = 0; i <= 255; i++) {

        // build the next IP address
        String addr = YourIPAddress;
        addr = addr.substring(0, addr.lastIndexOf('.') + 1) + i;
        InetAddress pingAddr = InetAddress.getByName(addr);

        // 50ms Timeout for the "ping"
        if (pingAddr.isReachable(iFace, 200, 50)) {
            Log.d("PING", pingAddr.getHostAddress());
        }
    }
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
like image 197
harism Avatar answered Nov 07 '22 15:11

harism