List devices on local network with ping

后端 未结 1 1568
臣服心动
臣服心动 2020-12-16 04:52

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

相关标签:
1条回答
  • 2020-12-16 05:38

    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) {
    }
    
    0 讨论(0)
提交回复
热议问题