2012-09-14 26 views
5

Yerel ağdaki tüm bağlı aygıtları listeleyen bir işlev oluşturmaya çalışıyorum. Yaptığım şey, herhangi bir adresi x.x.x.0 - x.x.x.255 adres alanına ping etmektir, ancak düzgün çalışmıyor gibi görünmüyor. Kodumu bir şekilde açıklayabilir veya genişletebilir misiniz? Telefondan (10.0.0.17) ve varsayılan ağ geçidinden (10.0.0.138) bir yanıt alıyorum. İkincisi orada olmamalıydı (aslında varsayılan ağ geçidinin ne olduğunu bilmiyorum ama bunu görmezden geleyim). IP'yi bu bilgisayardan kaçırıyorum.Yerel ağdaki ping pili aygıtları

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

Btw, Emulator kullanmıyorum, telefonumu kullanıyorum! – rtc11

cevap

9

İşte hile yapması gereken biraz değiştirilmiş döngü (veya en azından benim için çalıştı);

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

Bu daha iyi bir çözüm gibi görünüyor, ancak şimdi sadece yerel IP'yi telefonuma, dizüstü bilgisayarım veya sunucuma götürmüyorum. – rtc11