如何用java获取网卡地址(MAC Address)

来源:互联网 发布:电脑显示未识别的网络 编辑:程序博客网 时间:2024/05/01 23:54

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

        如何取得MAC Address,SUN没有提供官方的直接实现,这就要我们自己动脑了。你可以借助jni和C等第三方手段来间接获取,这里提供另外一种方法,也能满足需求,代码如下:

package com.pure.util;
import java.io.*;
import java.util.*;
import java.util.regex.*;

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(".*((:?[0-9a-f]{2}[-:]){5}[0-9a-f]{2}).*",Pattern.CASE_INSENSITIVE); 
 
 private final static List<String> getMacAddressList() throws IOException {
  final ArrayList<String> macAddressList = new ArrayList<String>();

  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 stderr
  new 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 stdout
  BufferedReader 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<String> addressList=getMacAddressList();
   StringBuffer sb=new StringBuffer();
   for (Iterator<String> iter = addressList.iterator(); iter.hasNext();) {
    sb.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();
  }
 }
}

可以看到,这里使用平台自带shell来取得网卡地址,然后用java对文本进行筛选,取得需要的网卡地址。


原创粉丝点击