When I was working on a project recently, I encountered a small problem and recorded it in my blog.
Because the project needs to obtain the WiFi-IP address of the current Android system, it is habitually searched on the Internet, and a code segment is used and tested. The Code is as follows:
1 try { 2 for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 3 NetworkInterface intf = en.nextElement(); 4 for (Enumeration<InetAddress> enumIpAddr = intf 5 .getInetAddresses(); enumIpAddr.hasMoreElements();) { 6 InetAddress inetAddress = enumIpAddr.nextElement(); 7 if (!inetAddress.isLoopbackAddress()) { 8 String ip = inetAddress.getHostAddress().toString(); 9 }10 }11 }12 } catch (SocketException ex) {13 ex.printStackTrace();14 }
As a result, a problem occurred during project delivery and the customer could not use it. As a result, the other party used a 3G card, and the IP address was obtained by the code above, resulting in a problem. The above code obtains the Wi-Fi and 3G network IP addresses.
If you only get the IP address of WiFi, the Code is as follows:
1 // only get the WiFi address 2 wifimanager wifimanage = (wifimanager) getsystemservice (context. wifi_service); // get wifimanager 3 // check whether WiFi is enabled 4 If (wifimanage. iswifienabled () {// when WiFi is not enabled, the IP address is 0.0.05 wifiinfo = wifimanage. getconnectioninfo (); 6 string IP = inttoip (wifiinfo. getipaddress (); 7}
1 // convert the obtained int to a real IP address. For more information, see the online tutorial. Modify 2 Private string inttoip (int I) {3 return (I & 0xff) + ". "+ (I> 8) & 0xff) + ". "+ (I> 16) & 0xff) + ". "+ (I> 24) & 0xff); 4}