Recent projects need to get the IP address of the mobile phone, check the information, found that the online information is not complete:
Online method One: (Get under WiFi)
Public String Gethostwifiip () {
Get WiFi Service
Wifimanager Wifimanager = (wifimanager) this.getsystemservice (Context.wifi_service);
Determine if WiFi is turned on
if (!wifimanager.iswifienabled ()) {
Wifimanager.setwifienabled (TRUE);
}
Wifiinfo wifiinfo = Wifimanager.getconnectioninfo ();
int ipAddress = wifiinfo.getipaddress ();
String IP = Inttoip (ipAddress);
return IP;
}
Private String Inttoip (int i) {
Return (I & 0xFF) + "." +
((I >> 8) & 0xFF) + "." +
((i >>) & 0xFF) + "." +
(I >> & 0xFF);
}
Online method Two: (Said to be universal, but not test)
public static String Gethostgprsip () {
try {
for (enumeration<networkinterface> en = networkinterface
. Getnetworkinterfaces (); En.hasmoreelements ();) {
NetworkInterface intf = En.nextelement ();
for (enumeration<inetaddress> ipaddr = intf.getinetaddresses (); ipaddr
. hasMoreElements ();) {
InetAddress inetaddress = Ipaddr.nextelement ();
if (!inetaddress.isloopbackaddress ()) {
return inetaddress.gethostaddress ();
}
}
}
} catch (SocketException ex) {
LOG.E ("Error", ex.tostring ());
} catch (Exception e) {
LOG.E ("Error", e.tostring ());
}
return null;
}
, so I collate the tests and test the results:
Public String Getipadd () {
Determine if WiFi is turned on
String ipstring = "";
Get WiFi Service
Wifimanager Wifimanager = (wifimanager) this.getsystemservice (Context.wifi_service);
if (wifimanager.iswifienabled ()) {
Wifiinfo wifiinfo = Wifimanager.getconnectioninfo ();
int ipAddress = wifiinfo.getipaddress ();
Format conversion
ipstring = (ipAddress & 0xFF) + "." + ((ipAddress >> 8) & 0xFF)
+ "." + ((ipAddress >> +) & 0xFF) + "."
+ ((ipAddress >>) & 0xFF);
} else {//If WiFi is not turned on, get 3G IP
try {
for (enumeration<networkinterface> en = networkinterface
. Getnetworkinterfaces (); En.hasmoreelements ();) {
NetworkInterface intf = En.nextelement ();
Traverse all the network card devices, the general mobile device only 2 cards, one of which is the loopback network card
for (enumeration<inetaddress> enumipaddr = intf
. getinetaddresses (); Enumipaddr.hasmoreelements ();) {
InetAddress inetaddress = Enumipaddr.nextelement ();
Filter out loopback cards and IPV6
if (!inetaddress.isloopbackaddress ()
&&! (inetaddress instanceof inet6address)) {
ipstring = Inetaddress.gethostaddress (). toString ();
}
}
}
} catch (SocketException ex) {
LOG.E ("TAG", "getipaddr ()" + ex.tostring ());
}
}
return ipstring;
}
Tested, whether it is under the WiFi or 3g, 2g signal can be, hope to help others!
How to get the IP address of the phone side