About getting the Wi-Fi-IP address of Android

Source: Internet
Author: User

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}

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.