android get the local ip
时间:2010-04-13 来源:nearfuture_qinyaomin
The obvious way to get the IP-Address of your device simply doesn’t work on Android.
The first thing I tried was using the WifiInfo.
1 2 3 |
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); |
But wait: ipAddress is an integer? Of course not. I also did the math but couldn’t find a way to get the IP out of this integer. So thats not the right way.
Another possibility I found was to create a socket connection and use the Socket instance to get the local ip address.
1 2 3 4 5 6 |
try { Socket socket = new Socket("www.droidnova.com", 80); Log.i("", socket.getLocalAddress().toString()); } catch (Exception e) { Log.i("", e.getMessage()); } |
The disadvantages should be clear:
- You generate traffic – may result in costs for the user
- Your program depend on the Server you create a socket connection to
- The same exceptions may be thrown for different reasons – bad if you want to display a message to tell the user what he should do to fix the problem
The right thing is to iterate over all network interfaces and iterate there over all ip addresses.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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; } |
So if this method returns null, there is no connection available.
If the method returns a string, this string contains the ip address currently used by the device independent of 3G or WiFi.