擷取手機IP地址的代碼:
public static 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 e) {// TODO: handle exceptionUtils.log("WifiPreference IpAddress---error-" + e.toString());}return null; }
但是在4.0 下 會出現類似fe80::b607:f9ff:fee5:487e的IP地址, 這個是IPV6的地址,我們需要獲得是的IPV4的地址,所以要在上訴代碼中加一個判斷
InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())
完整代碼如下:
public static 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() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) { return inetAddress.getHostAddress().toString(); } } }}catch (SocketException e) {// TODO: handle exceptionUtils.log("WifiPreference IpAddress---error-" + e.toString());}return null; }