7

ローカル ネットワークに接続されているすべてのデバイスを一覧表示する関数を作成しようとしています。私がしているのは、アドレス空間 xxx0 から xxx255 までの任意のアドレスに対して 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;
}
4

1 に答える 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) {
}
于 2012-09-14T17:33:03.020 に答える