刘政道 - 应用程序框架

《31天学会CRM项目开发(C#编程入门及项目实战)》作者,IT经理,程序员
  博客园  :: 新随笔  :: 联系 :: 管理

java取得网卡地址

Posted on 2010-12-28 10:39  刘政道  阅读(335)  评论(0编辑  收藏  举报
String macStr = "";//MAC网卡地址
try {
    InetAddress address = InetAddress.getLocalHost();//取得本地Ip地址
    System.out.println("getLocalHost:" + address.toString());
    //InetAddress address = InetAddress.getByName("192.168.46.53");
    NetworkInterface ni = NetworkInterface.getByInetAddress(address);
    if (ni != null) {
        byte[] mac = ni.getHardwareAddress();
        if (mac != null) {
            for (int i = 0; i < mac.length; i++) {
                System.out.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "");
                macStr = macStr + String.format("%02X%s",mac[i],(i < mac.length - 1) ? "-" : "");//格式化输出
            }
        } else {
            System.out.println("Address doesn't exist or is not accessible.");
        }
    } else {
        System.out.println("Network Interface for the specified address is not found.");
}
} catch (UnknownHostException ex) {
    ex.printStackTrace();
} catch (SocketException ex1) {
    ex1.printStackTrace();
}
System.out.println("macStr:" + macStr);