rtc*_*c11 7 networking android ping local
我正在尝试创建一个列出本地网络上所有连接设备的功能.我所做的是ping地址空间xxx0到xxx255的任何地址,但它似乎无法正常工作.有人能以某种方式解释或扩展我的代码吗?我从电话(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;
}
har*_*ism 11
这是一个稍微修改过的循环,应该可以解决这个问题(至少对我有用);
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) {
}
| 归档时间: | 
 | 
| 查看次数: | 4570 次 | 
| 最近记录: |