溫馨提示×

java如何獲取本地ip地址

小億
91
2024-08-17 09:32:36
欄目: 編程語言

在Java中獲取本地IP地址可以通過以下方式之一:

  1. 使用InetAddress類:
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    public static void main(String[] args) {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            System.out.println("Local IP Address: " + localhost.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用NetworkInterface類:
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class Main {
    public static void main(String[] args) {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
                        System.out.println("Local IP Address: " + inetAddress.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

這兩種方法都可以獲取本地IP地址,第一種方法使用了InetAddress類的getLocalHost()方法,直接獲取本地IP地址,而第二種方法通過遍歷所有網(wǎng)絡(luò)接口和對應(yīng)的InetAddress來獲取本地IP地址。

0