全部博文(135)
2010年(135)
分类: LINUX
2010-04-13 09:40:33
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("", 80); Log.i("", socket.getLocalAddress().toString()); } catch (Exception e) { Log.i("", e.getMessage()); } |
The disadvantages should be clear:
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.