2012-09-14 24 views
5

के साथ स्थानीय नेटवर्क पर सूची डिवाइस मैं एक ऐसा फ़ंक्शन बनाने की कोशिश कर रहा हूं जो स्थानीय नेटवर्क पर सभी कनेक्टेड डिवाइस सूचीबद्ध करता है। मैं क्या करता हूं पता पता x.x.x.0 से x.x.x.255 तक किसी भी पते को पिंग करना है, लेकिन यह ठीक से काम नहीं कर रहा है। क्या कोई मेरे कोड को किसी भी तरह समझा सकता है या बढ़ा सकता है? मुझे फोन से प्रतिक्रिया मिलती है (10.0.0.17) और एक डिफ़ॉल्ट गेटवे (10.0.0.138)। उत्तरार्द्ध भी वहां नहीं होना चाहिए (वास्तव में मुझे नहीं पता कि एक डिफ़ॉल्ट गेटवे क्या है लेकिन उसे अनदेखा करें)। हालांकि मैं इस कंप्यूटर से आईपी खो रहा हूँ।पिंग

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

यह एक बेहतर समाधान की तरह लगता है, लेकिन अब मैं केवल फोन पर स्थानीय आईपी प्राप्त कर रहा हूं, न कि मेरे लैपटॉप और न ही सर्वर। – rtc11

संबंधित मुद्दे