Original: http://www.cnblogs.com/android100/p/Android-get-ip.html
1. Use 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 turned on
- 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's Internet access rights
- <uses-permission android:name="Android.permission.INTERNET"></uses-permission >
Second, the code is as follows
- 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 inetaddress = Enumipaddr.nextelement ();
- if (!inetaddress.isloopbackaddress ())
- {
- return Inetaddress.gethostaddress (). toString ();
- }
- }
- }
- }
- catch (SocketException ex)
- {
- LOG.E ("Wifipreference IpAddress", ex.tostring ());
- }
- return null;
- }
Android Get IP Address