有的时候我们需要获得WIFI的IP地址获得手机网络的IP地址,这是一个工具类,专门解决这个问题,这里需要两个权限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" ></uses-permission><uses-permission android:name="android.permission.INTERNET" ></uses-permission>
第一个权限是获得WIFI的IP地址需要使用的,第二个权限是获得移动网络的IP需要使用的,代码如下:
public class GetIPAddressUtil {public static String getWifiIP(Context context) {String ip = null;WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);if (wifiManager.isWifiEnabled()) {WifiInfo wifiInfo = wifiManager.getConnectionInfo();int i = wifiInfo.getIpAddress();ip = (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)+ "." + (i >> 24 & 0xFF);}return ip;}public static String getMobileIP() {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("哎呀,出错了...", ex.toString());}return null;} }
完整演示Demo下载地址https://github.com/lenve/getIPAddress