如何通过java获取计算机的MAC地址和IP地址列表?

时间:2012-10-05 06:42:20

标签: java

我正在开发一个软件,我需要通过java代码获取计算机的IP地址和MAC地址列表。有没有办法获取IP地址和mac地址列表?

谢谢

2 个答案:

答案 0 :(得分:7)

从JDK 1.6开始,Java开发人员可以通过NetworkInterface类访问网卡详细信息。

            InetAddress ip;
    ip = InetAddress.getLocalHost();
    System.out.println("Current IP address : " + ip.getHostAddress());

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

    byte[] mac = network.getHardwareAddress();

    System.out.print("Current MAC address : ");

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < mac.length; i++) {
        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
    }
    System.out.println(sb.toString());

对于多个IP地址:

                    java.util.Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        en.hasMoreElements(); ) {
        NetworkInterface iface = en.nextElement();
        List<InterfaceAddress> addrs = iface.getInterfaceAddresses();
        //For each network interfaces iterate through each ip address
        for(InterfaceAddress addr : addrs) {
                         ip = addr.getAddress();
                          //Process the IP ...

答案 1 :(得分:1)

从java程序运行命令的示例代码

    Process p;
    String cmd="ifconfig-a";
    p = Runtime.getRuntime().exec(cmd);
    BufferedReader br = new BufferedReader(
    new InputStreamReader(p.getInputStream()));
    while ((s = br.readLine()) != null)
    System.out.println("line: " + s);
    p.waitFor();
    System.out.println ("exit: " + p.exitValue());
    p.destroy();

输出:

line: eth0      Link encap:Ethernet  HWaddr 00:13:D3:DE:5A:A4  --->MAC address in linux