JAVA获得网卡号

原创 2005年05月27日 19:41:00

I've written some code to determine the MAC address of a network adapter. This question has been floating around for years, so maybe we can come up with a solution that will work in at least some environments !

The following issues are open from my side:
- Will probably not run in applets
- Tested Windows / Linux only
- Tested J2SDK 1.4 only
- If a computer has more than one network adapters, only one MAC address will be returned
- will not run if user does not have permissions to run ifconfig/ipconfig (e.g. under linux this is typically only permitted for root)

Any comments are highly appreciated.
Holger


/** try to determine MAC address of local network card; this is done
    using a shell to run ifconfig (linux) or ipconfig (windows). The
    output of the processes will be parsed.

    <p>

    To run the whole thing, just type java NetworkInfo

    <p>

    Current restrictions:

    <ul>
       <li>Will probably not run in applets

       <li>Tested Windows / Linux only

       <li>Tested J2SDK 1.4 only

       <li>If a computer has more than one network adapters, only
           one MAC address will be returned

       <li>will not run if user does not have permissions to run
           ifconfig/ipconfig (e.g. under linux this is typically
           only permitted for root)
    </ul>

  */
 
import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;
 
public final class NetworkInfo {
 private final static String getMacAddress() throws IOException {
  String os = System.getProperty("os.name");
 
  try {
   if(os.startsWith("Windows")) {
    return windowsParseMacAddress(windowsRunIpConfigCommand());
   } else if(os.startsWith("Linux")) {
    return linuxParseMacAddress(linuxRunIfConfigCommand());
   } else {
    throw new IOException("unknown operating system: " + os);
   }
  } catch(ParseException ex) {
   ex.printStackTrace();
   throw new IOException(ex.getMessage());
  }
 }
 
 
 /*
  * Linux stuff
  */
 private final static String linuxParseMacAddress(String ipConfigResponse) throws ParseException {
  String localHost = null;
  try {
   localHost = InetAddress.getLocalHost().getHostAddress();
  } catch(java.net.UnknownHostException ex) {
   ex.printStackTrace();
   throw new ParseException(ex.getMessage(), 0);
  }
 
  StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "/n");
  String lastMacAddress = null;
 
  while(tokenizer.hasMoreTokens()) {
   String line = tokenizer.nextToken().trim();
   boolean containsLocalHost = line.indexOf(localHost) >= 0;
 
   // see if line contains IP address
   if(containsLocalHost && lastMacAddress != null) {
    return lastMacAddress;
   }
 
   // see if line contains MAC address
   int macAddressPosition = line.indexOf("HWaddr");
   if(macAddressPosition <= 0) continue;
 
   String macAddressCandidate = line.substring(macAddressPosition + 6).trim();
   if(linuxIsMacAddress(macAddressCandidate)) {
    lastMacAddress = macAddressCandidate;
    continue;
   }
  }
 
  ParseException ex = new ParseException
   ("cannot read MAC address for " + localHost + " from [" + ipConfigResponse + "]", 0);
  ex.printStackTrace();
  throw ex;
 }
 
 
 private final static boolean linuxIsMacAddress(String macAddressCandidate) {
  // TODO: use a smart regular expression
  if(macAddressCandidate.length() != 17) return false;
  return true;
 }
 
 
 private final static String linuxRunIfConfigCommand() throws IOException {
  Process p = Runtime.getRuntime().exec("ifconfig");
  InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
 
  StringBuffer buffer= new StringBuffer();
  for (;;) {
   int c = stdoutStream.read();
   if (c == -1) break;
   buffer.append((char)c);
  }
  String outputText = buffer.toString();
 
  stdoutStream.close();
 
  return outputText;
 }
 
 
 
 /*
  * Windows stuff
  */
 private final static String windowsParseMacAddress(String ipConfigResponse) throws ParseException {
  String localHost = null;
  try {
   localHost = InetAddress.getLocalHost().getHostAddress();
  } catch(java.net.UnknownHostException ex) {
   ex.printStackTrace();
   throw new ParseException(ex.getMessage(), 0);
  }
 
  StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "/n");
  String lastMacAddress = null;
 
  while(tokenizer.hasMoreTokens()) {
   String line = tokenizer.nextToken().trim();
 
   // see if line contains IP address
   if(line.endsWith(localHost) && lastMacAddress != null) {
    return lastMacAddress;
   }
 
   // see if line contains MAC address
   int macAddressPosition = line.indexOf(":");
   if(macAddressPosition <= 0) continue;
 
   String macAddressCandidate = line.substring(macAddressPosition + 1).trim();
   if(windowsIsMacAddress(macAddressCandidate)) {
    lastMacAddress = macAddressCandidate;
    continue;
   }
  }
 
  ParseException ex = new ParseException("cannot read MAC address from [" + ipConfigResponse + "]", 0);
  ex.printStackTrace();
  throw ex;
 }
 
 
 private final static boolean windowsIsMacAddress(String macAddressCandidate) {
  // TODO: use a smart regular expression
  if(macAddressCandidate.length() != 17) return false;
 
  return true;
 }
 
 
 private final static String windowsRunIpConfigCommand() throws IOException {
  Process p = Runtime.getRuntime().exec("ipconfig /all");
  InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
 
  StringBuffer buffer= new StringBuffer();
  for (;;) {
   int c = stdoutStream.read();
   if (c == -1) break;
   buffer.append((char)c);
  }
  String outputText = buffer.toString();
 
  stdoutStream.close();
 
  return outputText;
 }
 
 
 
 /*
  * Main
  */
 public final static void main(String[] args) {
  try {
   System.out.println("Network infos");
 
   System.out.println("  Operating System: " + System.getProperty("os.name"));
   System.out.println("  IP/Localhost: " + InetAddress.getLocalHost().getHostAddress());
   System.out.println("  MAC Address: " + getMacAddress());
  } catch(Throwable t) {
   t.printStackTrace();
  }
 }
}

Java/JSP获得客户端网卡MAC地址的三种方法解析

从网上查找资料java/jsp获得客户端(IE)网卡MAC地址的方法大概有三种。 1、通过命令方式,在客户端执行Ipconfig 等等 2、通过ActiveX的方法 3、通过向137的端口发送查...

java 获得网卡MAC地址

前阵子看到一篇文件,JAVA得到网卡物理地址(windows和Linux) ,当时觉得挺好,后来正好项目里有需要,就用了它,但好像有点问题.因为它是采用固定字符串搜索(if (line.indexO...

Java/JSP获得客户端网卡MAC地址的三种方法解析(附:获得真实IP)

Java/JSP获得客户端网卡MAC地址的三种方法解析 从网上查找资料java/jsp获得客户端(IE)网卡MAC地址的方法大概有三种。 1、通过命令方式,在客户端执行Ipconfig 等...
  • cactusz
  • cactusz
  • 2017年07月06日 15:49
  • 180

快速获得CUP序列号和网卡Mac地址

  • 2006年02月23日 09:05
  • 50KB
  • 下载

java 获取本机硬件信息 cpu 内存 硬盘 网卡等

1 下载安装sigar-1.6.4.zip     使用java自带的包获取系统数据,容易找不到包,尤其是内存信息不够准确,所以选择使用sigar获取系统信息。       下载地址:ht...

网卡唤醒计算机java

  • 2015年08月28日 12:19
  • 2KB
  • 下载

新浪旧事-JAVA之获取网卡物理地址

在JAVA中有时候会需要定位到某台电脑,而通过IP定位显然是不行的,有一种解决方案是通过定位到电脑的物理地址来定位电脑,这是本文要介绍的内容。     1. PhysicalAddressUtil ...
  • geloin
  • geloin
  • 2012年04月13日 09:18
  • 632

利用Java获取本机网卡的MAC地址

软件项目或者产品有时候会用到本机网卡的物理MAC地址,例如结合MAC地址进行登录验证等等,当然这种项目一般在局域网内运行,能相对提高系统的安全性。   下面列出了java读取MAC地址的工具方法,可...

java获取网卡的mac地址

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:JAVA获得网卡号
举报原因:
原因补充:

(最多只允许输入30个字)