Android Get IP Address
Recently done project, there is a demand is the Android device to obtain the current IP function, after a query to solve the data, record the implementation method.
1. Using WiFi
Set user Permissions First
<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE" ></uses-permission>
< Uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" ></uses-permission>
< Uses-permission android:name= "Android.permission.WAKE_LOCK" ></uses-permission>
Second, the code is as follows
public void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.main);
Get WIFI service
wifimanager Wifimanager = (wifimanager) getsystemservice (context.wifi_service);
Determine if WiFi is open if
(!wifimanager.iswifienabled ()) {
wifimanager.setwifienabled (true);
}
Wifiinfo wifiinfo = Wifimanager.getconnectioninfo ();
int ipaddress = wifiinfo.getipaddress ();
String IP = Inttoip (ipaddress);
EditText et = (edittext) Findviewbyid (r.id.edittext01);
Et.settext (IP);
}
Private String Inttoip (int i) {return
(I & 0xFF) + "." +
((I >> 8) & 0xFF) + "." + (
(i) ;> & 0xFF) + "." +
(I >> & 0xFF);
}
2. Using GPRS
First, set the user access rights
<uses-permission android:name= "Android.permission.INTERNET" ></uses-permission>
Second, the code is as follows
Public String getlocalipaddress ()
{
try
{
enumeration<networkinterface> en = Networkinterface.getnetworkinterfaces (); En.hasmoreelements ();)
{
NetworkInterface intf = En.nextelement ();
for (enumeration<inetaddress> enumipaddr = intf.getinetaddresses (); enumipaddr.hasmoreelements ();)
{
inetaddress inetaddress = Enumipaddr.nextelement ();
if (!inetaddress.isloopbackaddress ())
{return
inetaddress.gethostaddress (). toString ();
}
catch (SocketException ex)
{
log.e ("Wifipreference IPAddress", ex.tostring ());
}
return null;
}
Thank you for reading, I hope to help you, thank you for your support for this site!