此处的示例向您展示如何使用java.net.InetAddress该类获取IP或主机地址。要获取实例,InetAddress我们调用此类的静态方法,该方法为getLocalHost(),该方法返回本地主机地址。接下来,要获取IP地址,我们可以调用该getHostAddress()方法。package org.nhooo.example.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class LocalHostIpAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
System.out.println("IP Address = " + ip);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
此代码段的结果:IP Address = 192.168.0.102