Android general method for obtaining IP addresses (method for determining whether mobile phones are 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:

 

[Java]View
Plaincopy

  1. Wifimanager = (wifimanager) getsystemservice (wifi_service );
  2. Wifiinfo = wifimanager. getconnectioninfo ();
  3. 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:

 

[Java]View
Plaincopy

  1. Public String getlocalipaddress (){
  2. Try {
  3. For (enumeration <networkinterface> en = networkinterface. getnetworkinterfaces (); en. hasmoreelements ();){
  4. Networkinterface INTF = en. nextelement ();
  5. For (enumeration <inetaddress> enumipaddr = INTF. getinetaddresses (); enumipaddr. hasmoreelements ();){
  6. Inetaddress = enumipaddr. nextelement ();
  7. If (! Inetaddress. isloopbackaddress ()){
  8. Return inetaddress. gethostaddress (). tostring ();
  9. }
  10. }
  11. }
  12. } Catch (socketexception ex ){
  13. Log. E (log_tag, Ex. tostring ());
  14. }
  15. Return NULL;
  16. }

 

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

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.