Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 取得本機 IP:用 NetworkInterface 遍歷(Windows / Linux 通用)

取本機 IP 最直覺的做法是 InetAddress.getLocalHost(),但它依賴主機名稱解析,在多網卡或 hosts 設定不同的環境下常常取到 127.0.0.1,不可靠。比較穩健的方式是遍歷所有網路介面。

方法一:getLocalHost(簡單但受限)

String s = InetAddress.getLocalHost().toString();   // hostname/IP
String[] arr = s.split("/");
System.out.println("host name: " + arr[0]);
System.out.println("localhost IP: " + arr[1]);

方法二:遍歷 NetworkInterface(推薦)

import java.io.*;
import java.util.*;
import java.net.*;

public class GetIP {
    public static void main(String[] args) throws Exception {
        Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
        while (e.hasMoreElements()) {
            NetworkInterface n = e.nextElement();
            Enumeration<InetAddress> ee = n.getInetAddresses();
            while (ee.hasMoreElements()) {
                InetAddress i = ee.nextElement();
                System.out.println(i.getHostAddress());
            }
        }
    }
}

這段程式在 Windows 與 Linux 上都能正常運作,會列出所有介面上已設定的位址,包含 IPv6。

實務上的兩個補強

一是過濾掉 loopback 與未啟用的介面,只留真正對外的那張網卡:

if (n.isLoopbackAddress() || !n.isUp()) continue;

二是若只想要 IPv4,可再檢查 i instanceof Inet4Address。多網卡環境(例如同時有實體網卡、VPN、Docker 的 bridge)下,不做過濾的話呼叫端很容易拿到錯誤的位址。

Copyright © Linux教程網 All Rights Reserved