Android获取本机Mac地址和IP地址

1、获取Mac地址:

   在AndroidManifest.xml文件中添加权限: 

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

   获取:

public String getLocalMacAddress() {
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}

2、获取IP地址:

   在AndroidManifest.xml文件中添加权限:

<uses-permission android:name="android.permission.INTERNET"/>

   获取:

public String getLocalIpAddress() { 
        try { 
              String ipv4; 
              List<NetworkInterface>  nilist = 
			Collections.list(NetworkInterface.getNetworkInterfaces()); 
              for (NetworkInterface ni: nilist){ 
              	List<InetAddress>  ialist = Collections.list(ni.getInetAddresses()); 
                for (InetAddress address: ialist){ 
                   if (!address.isLoopbackAddress() && 
				InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress())){  
                        return ipv4; 
                    } 
                } 
            } 
           } catch (SocketException ex) { 
            Log.e("exception", ex.toString()); 
        } 
        return null; 
    }

mac

相关推荐