`

java获取网卡MAC地址,java获取网卡序列号的方法

阅读更多

    刚写的java获取网卡mac地址序列号的方法。在这里记录一下。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class MACAddress {
	public MACAddress() {
	}

	public static String getMACAddress() {

		String address = "";
		String os = System.getProperty("os.name");
		if (os != null && os.startsWith("Windows")) {
			try {
				String command = "cmd.exe /c ipconfig /all";
				Process p = Runtime.getRuntime().exec(command);
				BufferedReader br = new BufferedReader(new InputStreamReader(p
						.getInputStream()));
				String line;
				while ((line = br.readLine()) != null) {
					if (line.indexOf("Physical Address") > 0) {
						int index = line.indexOf(":");
						index += 2;
						address = line.substring(index);
						break;
					}
				}
				br.close();
				return address.trim();
			} catch (IOException e) {
			}
		}
		return address;
	}

	public static void main(String[] args) {
		// System.out.println(""+MACAddress.getMACAddress());
		try {
			// 枚举所有网络接口设备
			Enumeration intefaces = NetworkInterface.getNetworkInterfaces();
			// 循环处理每一个网络接口设备
			while (intefaces.hasMoreElements()) {
				NetworkInterface face = (NetworkInterface) intefaces
						.nextElement();
				if (face.getName().length() >= 3) {
					if ((face.getName()).substring(0, 3).equals("eth") || (face.getName()).substring(0, 3).equals("net")) {

						byte[] mac = face.getHardwareAddress();
						if (mac != null && mac.length == 6) {
							System.out.println("网卡显示名称:"
									+ face.getDisplayName());
							System.out.println("网卡设备名称:" + face.getName());
							System.out.println("MAC地址:" + bytes2mac(mac));
//							break;
						}
					}
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static String bytes2mac(byte[] bytes) {
		if (bytes.length != 6) {
			System.out.println("地址错误");
			return null;
		}
		StringBuffer macString = new StringBuffer();
		byte currentByte;
		for (int i = 0; i < bytes.length; i++) {
			currentByte = (byte) ((bytes[i] & 240) >> 4);
			macString.append(Integer.toHexString(currentByte));
			currentByte = (byte) (bytes[i] & 15);
			macString.append(Integer.toHexString(currentByte));
			macString.append("-");
		}
		macString.delete(macString.length() - 1, macString.length());

		return macString.toString().toUpperCase();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics