`

IP地址的获取及解析

阅读更多
获取IP地址
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

解析IP地址
private String parseIP(int ip) {

	StringBuffer sb = new StringBuffer();

	int x, y;
	y = ip;

	while (true) {

		x = y;
		y = x >> 8;

		sb.append(Integer.toString(x - (y << 8)));

		if (y > 0) {
			sb.append(".");
		} else {
			break;
		}
	}

	return sb.toString();
}

这样我们就可以把1677895872这样的数字转换成192.168.2.100了

注意:调用WifiManager需要在AndroidManifest里添加
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

===============================================================

另一种获取IP地址的方法
public String getLocalIpAddress() {

	try {
		String ipv4;

		for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {

			NetworkInterface intf = en.nextElement();
			for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {

				InetAddress address = enumIpAddr.nextElement();
				if (!address.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ipv4 = address
									.getHostAddress())) {
					return ipv4;
				}
			}
		}

	} catch (SocketException ex) {
		ex.printStackTrace();
	}

	return null;
}

这种方法需要添加下述permission
<uses-permission android:name="android.permission.INTERNET" />
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics