Get IP address on Android
Recently, when I was working on a project, one of the requirements is to obtain the current IP function of Android devices. After querying information, I solved it and recorded the implementation method.
1. Use WIFI
First set user permissions
<uses-permission Android:name=".ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name=".CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name=".WAKE_LOCK"></uses-permission>
Secondly, the code is as follows
public void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(); //Get wifi service WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); //Discern whether wifi is enabled if (!()) { (true); } WifiInfo wifiInfo = (); int ipAddress = (); String ip = intToIp(ipAddress); EditText et = (EditText)findViewById(.EditText01); (ip); } private String intToIp(int i) { return (i & 0xFF ) + "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ( i >> 24 & 0xFF) ; }
2. Use GPRS
First, set user access permissions
<uses-permission android:name=""></uses-permission>
Secondly, the code is as follows
public String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = (); ();) { NetworkInterface intf = (); for (Enumeration<InetAddress> enumIpAddr = (); ();) { InetAddress inetAddress = (); if (!()) { return ().toString(); } } } } catch (SocketException ex) { ("WifiPreference IpAddress", ()); } return null; }
Thank you for reading, I hope it can help you. Thank you for your support for this site!