alex09 发表于 2013-1-15 02:51:04

java 取MAC地址

我们经常要取得一些和机器硬件相关的信息来进行一些特殊授权的操作,如文件加密等,这时,针对网卡地址的处理是一种不错的选择,因为硬件厂商已经将网卡的编号固化到了网卡上,而这个编号是全球唯一的,绝对不会重复。

如何取得MAC Address,SUN没有提供官方的直接实现,这就要我们自己动脑了。你可以借助jni和C等第三方手段来间接获取,这里提供另外一种方法,也能满足需求,代码如下:
package com.pure.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;public class MacAddress {private static final String[] windowsCommand = { "ipconfig", "/all" };private static final String[] linuxCommand = { "/sbin/ifconfig", "-a" };private static final Pattern macPattern = Pattern.compile(".*((:?{2}[-:]){5}{2}).*",Pattern.CASE_INSENSITIVE);private final static List getMacAddressList() throws IOException {final ArrayList macAddressList = new ArrayList();final String os = System.getProperty("os.name");final String[] command;if (os.startsWith("Windows")) {command = windowsCommand;} else if (os.startsWith("Linux")) {command = linuxCommand;} else {throw new IOException("Unknown operating system: " + os);}final Process process = Runtime.getRuntime().exec(command);// Discard the stderrnew Thread() {public void run() {try {InputStream errorStream = process.getErrorStream();while (errorStream.read() != -1) {}errorStream.close();} catch (IOException e) {e.printStackTrace();}}}.start();// Extract the MAC addresses from stdoutBufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));for (String line = null; (line = reader.readLine()) != null;) {Matcher matcher = macPattern.matcher(line);if (matcher.matches()) {// macAddressList.add(matcher.group(1));macAddressList.add(matcher.group(1).replaceAll("[-:]", ""));}}reader.close();return macAddressList;}public static String getMacAddress() {try {List addressList = getMacAddressList();StringBuffer sb = new StringBuffer();for (Iterator iter = addressList.iterator(); iter.hasNext();) {sb.append("\n").append(iter.next());}return sb.toString();} catch (IOException e) {return null;}}public final static void main(String[] args) {try {System.out.println(" MAC Address: " + getMacAddress());} catch (Throwable t) {t.printStackTrace();}}}
页: [1]
查看完整版本: java 取MAC地址