IT技术浅谈
联系我们
IT技术浅谈

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

发布人:admin 发布时间:2019-01-16

 获取手机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; 
	}

http://www.bkjia.com/Androidjc/433485.htmlwww.bkjia.comtruehttp://www.bkjia.com/Androidjc/433485.htmlTechArticle获取手机IP地址的代码: public static String getLocalIpAddress(){try{ for (EnumerationNetworkInterface en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)...

本文源自: 环亚娱乐

上一篇:基于zepto的插件之移动端无缝向上滚动并上下触摸滑动实例代码,zepto实例
下一篇:没有了