Android中获取设备的IP

 在wifi环境下,可以通过WifiInfo来获取设备的ip

Java代码 复制代码 收藏代码
  1. public String getIpAddress() {
  2. WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
  3. WifiInfo wifiInfo = wifiManager.getConnectionInfo();
  4. int ipAddress = wifiInfo.getIpAddress();
  5. int[] ipAddr = new int[4];
  6. ipAddr[0] = ipAddress & 0xFF;
  7. ipAddr[1] = (ipAddress >> 8) & 0xFF;
  8. ipAddr[2] = (ipAddress >> 16) & 0xFF;
  9. ipAddr[3] = (ipAddress >> 24) & 0xFF;
  10. return new StringBuilder().append(ipAddr[0]).append(".").append(ipAddr[1]).append(".").append(ipAddr[2])
  11. .append(".").append(ipAddr[3]).append(".").toString();
  12.  
  13. }
	public String getIpAddress() {
		WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		int[] ipAddr = new int[4];
		ipAddr[0] = ipAddress & 0xFF;
		ipAddr[1] = (ipAddress >> 8) & 0xFF;
		ipAddr[2] = (ipAddress >> 16) & 0xFF;
		ipAddr[3] = (ipAddress >> 24) & 0xFF;
		return new StringBuilder().append(ipAddr[0]).append(".").append(ipAddr[1]).append(".").append(ipAddr[2])
				.append(".").append(ipAddr[3]).append(".").toString();

	}



执行上面的代码需要

Xml代码 复制代码 收藏代码
  1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />



当然也可通过jdk总的NetworkInterface来获取的,就是遍历所有的网络接口,获取到非loopback ip

Java代码 复制代码 收藏代码
  1. public String getLocalIpAddress() {
  2. try {
  3. for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
  4. NetworkInterface intf = en.nextElement();
  5. for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
  6. InetAddress inetAddress = enumIpAddr.nextElement();
  7. if (!inetAddress.isLoopbackAddress()) {
  8. return inetAddress.getHostAddress().toString();
  9. }
  10. }
  11. }
  12. } catch (SocketException ex) {
  13. Log.e("", ex.toString());
  14. }
  15. return null;
  16. }  

你可能感兴趣的:(android,设备,的)