android中获取ip地址和mac地址

在android编程中,有时候我们需要获取本机的IP地址和MAC地址,本文简单的给出获取IP和MAC的实例

一、获取IP地址

public static byte[] getLocalIpAddress() {
		try {
			for (Enumeration en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				if (intf.getName().equals("usbnet0")) {
					continue;
				}
				for (Enumeration enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& (inetAddress instanceof Inet4Address)) {
						// String x = inetAddress.getHostAddress();
						return inetAddress.getAddress();

					}
				}
			}
		} catch (SocketException ex) {
			Log.e(TAG, ex.toString());
		}
		return null;
	}

二 、 获取不同网卡的IP地址

//获取特定网络接口的IP,such as eth0,wlan0
	public static byte[] getLocalIpAddress(String name){
		try {
			for (Enumeration en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				if (intf.getName().equals(name)) {
				    for (Enumeration enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					    InetAddress inetAddress = enumIpAddr.nextElement();
					    if (!inetAddress.isLoopbackAddress()
							&& (inetAddress instanceof Inet4Address)) {
						    return inetAddress.getAddress();

					    }
				    }
				}
			}
		} catch (SocketException ex) {
			Log.e(TAG, ex.toString());
		}
		return null;
		
	}

三、 获取MAC地址

public static byte[] getMacAddress() {
		Enumeration interfaces = null;
		try {
			interfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		while (interfaces.hasMoreElements()) {
			final NetworkInterface ni = interfaces.nextElement();
			try {
				if (ni.isLoopback() || ni.isPointToPoint() || ni.isVirtual())
					continue;
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			byte[] macAddress = null;
			try {
				macAddress = ni.getHardwareAddress();
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (macAddress != null && macAddress.length > 0)
				return macAddress;
		}
		return null;
	}

上述三个实例都是项目实践,大家可以放心使用。

你可能感兴趣的:(android)