列出本地网络上的设备并使用ping命令

7
我正在尝试创建一个列出本地网络上所有连接设备的函数。我所做的是ping地址空间 x.x.x.0 到 x.x.x.255 中的任何地址,但它似乎无法正常工作。有谁能解释或以某种方式扩展我的代码吗?我确实从手机 (10.0.0.17) 和默认网关 (10.0.0.138) 收到响应。后者甚至不应该存在(事实上,我不知道默认网关是什么,但请忽略这一点)。但我错过了来自这台计算机的 IP。
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;
}

顺便说一下,我不使用模拟器,我用我的手机! - rtc11
1个回答

12

这是一个稍作修改的循环,应该能解决问题(至少对我有效);

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) {
}

1
这似乎是一个更好的解决方案,但现在我只能在手机上获得本地IP地址,而无法获取我的笔记本电脑或服务器的IP地址。 - rtc11
我看到了这个函数块主线程,如何解决?提前致谢。 - famfamfam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接