2012-09-14 5 views
5

ローカルネットワーク上のすべての接続デバイスを一覧表示する機能を作成しようとしています。 アドレス空間x.x.x.0からx.x.x.255までの任意のアドレスに対してpingを実行しますが、正しく動作しないようです。誰かが私のコードを何らかの方法で説明したり拡張したりできますか?私は電話(10.0.0.17)とデフォルトゲートウェイ(10.0.0.138)から応答を受け取ります。後者はそこにいてはいけません(実際にはデフォルトゲートウェイが何であるか分かりませんが無視してください)。私はこのコンピュータからIPを紛失しています。pingを使用してローカルネットワーク上のデバイスを一覧表示する

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; 
} 
+0

エミュレータを使用していない私は私の携帯電話を使用しています! – rtc11

答えて

9

トリックを行う必要のあるループが少し修正されています(少なくとも私にとってはうまくいきました)。

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を取得するだけです。 – rtc11

関連する問題