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
- Wifimanager = (wifimanager) getsystemservice (wifi_service );
- Wifiinfo = wifimanager. getconnectioninfo ();
- 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
- 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 = enumipaddr. nextelement ();
- If (! Inetaddress. isloopbackaddress ()){
- Return inetaddress. gethostaddress (). tostring ();
- }
- }
- }
- } Catch (socketexception ex ){
- Log. E (log_tag, Ex. tostring ());
- }
- Return NULL;
- }
When my mobile phone is in the flight status, the obtained IP address is blank, just in line with the requirements !!!