2012-09-14 45 views
5

我試圖創建一個列出本地網絡上所有連接的設備的功能。 我所做的是將任何地址從地址空間x.x.x.0 ping到x.x.x.255,但它似乎不能正常工作。任何人都可以解釋或擴展我的代碼?我確實收到了電話(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