java获取网卡MAC地址,java获取网卡序列号的方法_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java获取网卡MAC地址,java获取网卡序列号的方法

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

 2011/9/9 8:14:45  h271665724  http://java161.iteye.com  我要评论(0)
  • 摘要:刚写的java获取网卡mac地址序列号的方法。在这里记录一下。importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.NetworkInterface;importjava.net.SocketException;importjava.util.Enumeration;publicclassMACAddress{publicMACAddress()
  • 标签:方法 Java Mac

??? 刚写的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();
	}
}

?

发表评论
用户名: 匿名