JDK6新特性,JAVA获得机器MAC地址的方法

本文详细介绍了如何使用Java编程语言,结合JDK6及JDK1.6的新特性,实现获取本地计算机所有网卡的MAC地址。包括传统的ipconfig方法和JDK6的API方法。

http://www.cnblogs.com/cyjch/archive/2012/02/06/2340368.html


这个代码包含了以前常见的用Runtime实现的方法,已经使用JDK1.6新特性实现的方法。

1.import java.io.BufferedReader;
2.import java.io.InputStreamReader;
3.import java.net.NetworkInterface;
4.import java.util.Enumeration;
5./**
6. * JDK6新特性,JAVA获得机器MAC地址的方法
7. *
8. * @author 老紫竹(Java世纪网,java2000.net)
9. */
10.publicclass Test {
11// 返回一个字节的十六进制字符串
12static String hexByte(byte b) {
13.    String s = "000000" + Integer.toHexString(b);
14.    return s.substring(s.length() - 2);
15.  }
16.  publicstaticvoid main(String[] args) throws Exception {
17.    System.out.println("本机器的所有的网卡MAC发下:");
18.    getMacOnWindow();
19.    getMac();
20.  }
21/**
22.   * JDK1.6新特性获取网卡MAC地址
23.   */
24.  publicstaticvoid getMac() {
25.    try {
26.      Enumeration<NetworkInterface> el = NetworkInterface.getNetworkInterfaces();
27.      while (el.hasMoreElements()) {
28.        byte[] mac = el.nextElement().getHardwareAddress();
29.        if (mac == null)
30.          continue;
31.        StringBuilder builder = new StringBuilder();
32.        for (byte b : mac) {
33.          builder.append(hexByte(b));
34.          builder.append("-");
35.        }
36.        builder.deleteCharAt(builder.length() - 1);
37.        System.out.println(builder);
38.      }
39.    } catch (Exception exception) {
40.      exception.printStackTrace();
41.    }
42.  }
43/**
44.   * 原始的获取网卡MAC地址
45.   */
46.  publicstaticvoid getMacOnWindow() {
47.    try {
48.      String mac = null;
49.      Process process = Runtime.getRuntime().exec("ipconfig /all");
50.      BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream()));
51.      for (String line = buffer.readLine(); line != null; line = buffer.readLine()) {
52.        int index = line.indexOf("Physical Address");
53.        if (index <= 0) {
54.          continue;
55.        }
56.        mac = line.substring(index + 36);
57.        break;
58.      }
59.      buffer.close();
60.      process.waitFor();
61.      System.out.println(mac);
62.    } catch (Exception exception) {
63.      exception.printStackTrace();
64.    }
65.  }
66.}

  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值