zoukankan      html  css  js  c++  java
  • JDK6新特性,JAVA获得机器MAC地址的方法

    这个代码包含了以前常见的用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.  // 返回一个字节的十六进制字符串
    12.  static 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.}
    

      

  • 相关阅读:
    Compact Framework访问内嵌资源文件
    RBAC权限设计图 [转]
    c# 中判断用户是否按下CTRL键
    分享开发soket经验 我的基于socket的持久层 [转]
    没事教宝宝画画
    界面开发(一)[转]
    Winform中多国语言窗体的设计以及.NET中资源文件的使用[转]
    我眼中的理想系统
    C# WinForm开发系列 Socket/WCF/Rometing/Web Services[转]
    基于RBAC的权限设计模型[转]
  • 原文地址:https://www.cnblogs.com/cyjch/p/2340368.html
Copyright © 2011-2022 走看看