溫馨提示×

java怎么獲取linux的ip地址

小億
184
2024-01-27 21:00:50
欄目: 編程語言

Java中獲取Linux的IP地址可以使用InetAddress類的相關(guān)方法。下面是獲取本地IP地址的示例代碼:

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("IP Address: " + localhost.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

這段代碼使用getLocalHost()方法獲取本地主機的InetAddress對象,然后使用getHostAddress()方法獲取IP地址。

0