【问题标题】:List devices on local network with ping使用 ping 列出本地网络上的设备
【发布时间】:2013-10-22 06:47:49
【问题描述】:

我正在尝试创建一个列出本地网络上所有已连接设备的函数。 我所做的是将地址空间 x.x.x.0 到 x.x.x.255 的任何地址 ping 通,但它似乎无法正常工作。谁能以某种方式解释或扩展我的代码?我确实收到了电话 (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;
}

【问题讨论】:

  • 顺便说一句,我没有用模拟器,我用我的手机!

标签: android networking local ping


【解决方案1】:

这里是稍微修改过的循环,应该可以解决问题(或者至少对我有用);

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

【讨论】:

  • 这似乎是一个更好的解决方案,但现在我只能在手机上获取本地 IP,而不是我的笔记本电脑和服务器。
  • 我看到这个功能块mainthread,怎么解决?提前致谢
猜你喜欢
  • 2023-02-17
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
相关资源
最近更新 更多