android – 使用ping列出本地网络上的设备

前端之家收集整理的这篇文章主要介绍了android – 使用ping列出本地网络上的设备前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个列出本地网络上所有连接设备的功能.
我所做的是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;
}
@H_404_5@

解决方法

这是一个稍微修改过的循环,应该可以解决这个问题(至少对我有用);
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) {
}
@H_404_5@ @H_404_5@ 原文链接:https://www.f2er.com/android/316392.html

猜你在找的Android相关文章