在 Java 中,可以使用 InetAddress 类来获取 IP 地址。
以下是一个示例,展示如何使用 InetAddress 获取本机的 IP 地址:
import java.net.InetAddress;
public class Main {
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
String ipAddr = addr.getHostAddress();
System.out.println("本机的 IP 地址是:" + ipAddr);
}
}
如果希望获取其他主机的 IP 地址,可以使用以下代码:
import java.net.InetAddress;
public class Main {
public static void main(String[] args) throws Exception {
String hostname = "www.example.com";
InetAddress addr = InetAddress.getByName(hostname);
String ipAddr = addr.getHostAddress();
System.out.println(hostname + " 的 IP 地址是:" + ipAddr);
}
}
在这两个示例中,InetAddress.getLocalHost() 方法用于获取本机的 IP 地址,而 InetAddress.getByName(hostname) 方法用于通过主机名获取 IP 地址。