java取MAC地址

jdk1.6中,NetworkInterface这个类提供了getHardwareAddress()方法,可以获得机器的MAC地址
public class Test7 {

	public static void main(String...args) throws IOException{
		Enumeration enums = NetworkInterface.getNetworkInterfaces();
		NetworkInterface net = null;
		while(enums.hasMoreElements()){
			net = (NetworkInterface) enums.nextElement();
			print(net.getDisplayName(), net.getHardwareAddress());
		}
	}
	
	private static void print(String name, byte[] mac){
		if(mac == null || mac.length==0){
			System.out.println(name+": no MAC");
			return ;
		}

		System.out.print(name+": ");
		int m = 0;
		for(int i=0;i<mac.length;i++){
			//byte表示范围-128~127,因此>127的数被表示成负数形式,这里+256转换成正数
			m = mac[i]<0?(mac[i]+256):mac[i];
			System.out.print(Integer.toHexString(m).toUpperCase()+"\t");
		}
		System.out.println();
	}
}



当然也可以调用Runtime.exec("ipconfig /all")得到InputStream再用正则提取出mac地址。

你可能感兴趣的:(java)