WEB开发网
开发学院手机开发Android 开发 android4.0 获取手机IP地址的问题 阅读

android4.0 获取手机IP地址的问题

 2012-09-06 16:07:52 来源:WEB开发网   
核心提示: 获取手机IP地址的代码:public static String getLocalIpAddress(){try{ for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElem

 获取手机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 exception
			Utils.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 exception
			Utils.log("WifiPreference IpAddress---error-" + e.toString());
		}
		
		return null; 
	}

Tags:android 获取 手机

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接