01.Test:代码演示获取本地 IP和指定 IP
public class InetAddressTest {
public static void main(String[] args) {
try {
//创建一个InetAddress对象
InetAddress localHost = InetAddress.getLocalHost();
//返回 IP 地址字符串
String hostAddress = localHost.getHostAddress();
System.out.println(hostAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
输出
192.168.3.7
02.Test:代码演示获取域名指定 IP
public class InetAddressTest2 {
public static void main(String[] args) {
try {
//创建一个InetAddress对象
InetAddress inetAddress = InetAddress.getByName("www.baidu.com");
//获取此 IP 地址的主机名包含域名
System.out.println(inetAddress);
//获取此 IP 地址的主机名
String hostAddress = inetAddress.getHostAddress();
System.out.println(hostAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
输出
www.baidu.com/61.135.169.121
61.135.169.121