When logging in in the project, the server requires to verify the IP of the mobile device. The following is the packaged IP acquisition tool class:
/** * Created by Michael on 2017/2/28. */ public class DeviceIpAddressUtil { public static String getIPAddress(Context context) { NetworkInfo info = ((ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); if (info != null && info.isConnected()) { if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//Currently using 2G/3G/4G network try { //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces(); 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() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace (); } } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//Currently using wireless network WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//Get IPV4 address return ipAddress; } } else { //There is currently no network connection, please open the network in the settings } return null; } /** * Convert the obtained IP of type int to type String * * @paramip * @return */ public static String intIP2StringIP(int ip) { return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF); } }