android 获取手机ip地址

android 获取手机ip地址,3g网络和wifi网络都有效,亲测。

/**
	 * 网络状态改变后,查询ip,过滤出ipv4
	 * @return ipv4地址
	 * @throws SocketException
	 */
	public String getIpAddress() throws SocketException{
		String ipaddress = "";
		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()) {
						ipaddress = inetAddress.getHostAddress().toString();
						//过滤掉ipv6
						if(!ipaddress.contains("::")){//ipV6的地址
							return ipaddress ;
						}
					}
				}
		}
		return ipaddress;
	}

   

猜你喜欢

转载自agehua.iteye.com/blog/2244445