2011-06-10 28 views
1

我想知道可以检测Android设备的IP地址和Android客户端名称的代码,以便在我们的应用程序中使用此IP地址和客户端名称。代码检测Android设备自己的IP地址?

任何人都可以帮助我请... 在此先感谢。

回答

7

这会告诉你你自己的IP地址,如果你在你的Android手机上运行它。

try{ 
     InetAddress ownIP=InetAddress.getLocalHost(); 
     System.out.println("IP of my Android := "+ownIP.getHostAddress()); 
     }catch (Exception e){ 
     System.out.println("Exception caught ="+e.getMessage()); 
     } 

如果你想知道你的广告应用程式结合的任何客户端的IP地址使用

Socket socket = serverSocket.accept(); // accept connection            


        System.out.println("Remote IP:"+socket.getInetAddress()); 

        System.out.println("Remote Port:"+socket.getPort());     
+0

GUD!那么y没有ü接受我的答案? – Harinder 2011-06-10 12:50:16

+2

它显示回环地址作为主机IP .. – Mak 2011-06-13 06:45:49

4
public String getLocalIpAddress() 
{ 
    try { 
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
      NetworkInterface intf = en.nextElement(); 
      for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
       InetAddress inetAddress = enumIpAddr.nextElement(); 
       if (!inetAddress.isLoopbackAddress()) { 
        return inetAddress.getHostAddress().toString(); 
       } 
      } 
     } 
    } catch (SocketException ex) { 
     Log.e(LOG_TAG, ex.toString()); 
    } 

    return null; 
} 
+0

参考:http://www.droidnova.com/get-the-ip-address-of-your-device,304.html – Mak 2011-08-26 08:29:07