Android advanced tutorial (11)-android general method for obtaining IP addresses (determining whether a mobile phone is connected to the Internet )!!!

Source: Internet
Author: User

Hello everyone, let's talk about some methods for Android to obtain IP addresses. In our development, we have determined whether the mobile phone is connected to the Internet or whether we want to obtain the IP address of the current mobile phone, of course, the sum of Wi-Fi connections

The IP addresses of our 3g cards are certainly different.

 

First, I tried the following method:

 

Wifimanager = (wifimanager) getsystemservice (response); <br/> wifiinfo = wifimanager. getconnectioninfo (); <br/> int IPaddress = wifiinfo. getipaddress ();

But the result is actually an integer. I tried to use some mathematical methods and it was not successful !, Therefore, this method is not advisable!

 

Finally, I checked some information and found that the following method is more common. I tried the WiFi and G3 cards and obtained the IP Address: the code is as follows:

 

Public String getlocalipaddress () {<br/> try {<br/> for (enumeration <networkinterface> en = networkinterface. getnetworkinterfaces (); en. hasmoreelements ();) {<br/> networkinterface INTF = en. nextelement (); <br/> for (enumeration <inetaddress> enumipaddr = INTF. getinetaddresses (); enumipaddr. hasmoreelements ();) {<br/> inetaddress = enumipaddr. nextelement (); <br/> If (! Inetaddress. isloopbackaddress () {<br/> return inetaddress. gethostaddress (). tostring (); <br/>}< br/>}catch (socketexception ex) {<br/> log. E (log_tag, Ex. tostring (); <br/>}< br/> return NULL; <br/>}

 

When my mobile phone is in the flight status, the obtained IP address is blank, just in line with the requirements !!!

 

Hope to help you! Thank you ~

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.