2015-03-04

[Java] 取得本地端 IP 與 MAC

import java.net.InetAddress;
import java.net.NetworkInterface;

public class TestInetAddress {

    public static void main(String[] args) throws Exception {
        InetAddress ip = InetAddress.getLocalHost();

        System.out.println("Current IP address : " + ip.getHostAddress());
        // Current IP address : 192.168.0.109

        System.out.println(ip.getCanonicalHostName());
        // 192.168.0.109

        System.out.println(ip.getHostName());
        // jaxhu-PC



        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

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

        System.out.println("Current MAC address : " + sb.toString());
        // Current MAC address : 38-2C-4A-B4-C3-24

        System.out.println(network.getDisplayName());
        // Realtek PCIe GBE Family Controller

        System.out.println(network.getName());
        // eth3
    }
}

參考自:How to get MAC address in Java : Mkyong

0 回應: