Board logo

标题: Java实现读取本机网卡Mac地址 [打印本页]

作者: qingqing3721    时间: 2012-5-13 10:06     标题: Java实现读取本机网卡Mac地址

本方法次要用来限制系统在其他的机器上运行.其实原理简单的很.没有调用第三方插件.代码如下:
  package com.users.util;
  import java.io.*;
  import java.util.*;
  import java.util.regex.*;
  public class NetID {
  String IPCONFIG_COMMAND_WIN = "ipconfig /all";
  boolean realMac = true;
  String unique = "";
  public static String getMacAddress() {
  NetID hwid = new NetID();
  return hwid.getUnique().trim();
  }
  private String getUnique() {
  String os = System.getProperty("os.name");
  if (os.viishowstartsWith("Windows")) {
  return getUniqueWindows();
  }else {
  return "";
  }
  }
  private String getUniqueWindows() {
  String ipConfigResponse = null;
  try {
  ipConfigResponse = runConsoleCommand(IPCONFIG_COMMAND_WIN);
  }
  catch (IOException e) {
  e.printStackTrace();
  }
  StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
  while (tokenizer.hasMoreTokens()) {
  String line = tokenizer.nextToken().trim();
  int macAddressPosition = line.indexOf(":");
  if (macAddressPosition = 0) {
  continue;
  }
  String macAddressCandidate = line.substring(macAddressPosition + 1).
  trim();
  if (isMacAddWin(macAddressCandidate)) {
  if (realMac == true) {
  generateUnique(macAddressCandidate);
  }
  else {
  realMac = true;
  }
  }
  }
  return unique;
  }  private String runConsoleCommand(String command) throws IOException {
  Process p = Runtime.getRuntime().exec(command);
  InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
  StringBuffer buffer = new StringBuffer();
  while (true) {
  int c = stdoutStream.read();
  if (c == -1) {
  break;
  }
  buffer.append( (char) c);
  }
  String outputText = buffer.toString();
  stdoutStream.close();
  return outputText;
  }
  private boolean isMacAddWin(String macAddressCandidate) {
  Pattern macPattern = Patternpile("[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}-[0-9a-fA-F]{2}");
  Matcher m = macPattern.matcher(macAddressCandidate);
  return m.matches();
  }
  private boolean isMacAddOSX(String macAddressCandidate) {
  if (macAddressCandidate.length() != 17) {
  return false;
  }
  else {
  return true;
  }
  }
  private void generateUnique(String macAddress) {
  if (unique == "") {
  unique += macAddress;
  }
  else {
  unique += "#";
  unique += macAddress;
  }
  }
  public static void main(String [] args) {
  System.out.println(NetID.getMacAddress());
  }
  }




欢迎光临 编程开发论坛 (http://bbs.lihuasoft.net/) Powered by Discuz! 6.0.0