java.net包中的InetAddress类用于封装IP地址DNS。要创建InetAddress的实例,可以使用工厂方法,因为此类没有可用的的构造方法。
方法 | 说明 |
static InetAddress getLocalHost() | 返回本地主机InetAddress对象 |
static InetAddress getByName(String hostName) | 为主机名为hostName的主机返回InetAddress对象 |
static InetAddress[ ] getAllByName(String hostName) | 为主机名为hostName的所有可能主机返回InetAddress对象组
|
String | getHostAddress() 返回 IP 地址字符串(以文本表现形式)。 |
String | getHostName() 获取此 IP 地址的主机名。 |
import java.net.InetAddress;
import java.util.Arrays;
public class InetAddressTest {
public static void main(String[] args) throws Exception {
// 直接这样写, 默认的指向我们这个电脑
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
System.out.println(localHost.getHostName());
System.out.println(localHost.getHostAddress());
InetAddress localHost2 = InetAddress.getByName("LAPTOP-NN58DDA7");
System.out.println(localHost2);
InetAddress localHost3 = InetAddress.getByName("192.168.199.153");
System.out.println(localHost3);// /192.168.199.153
// 根据[百度服务器主机名] 获取百度服务器InetAddress对象
InetAddress baiduAddress = InetAddress.getByName("www.baidu.com");
System.out.println(baiduAddress);
InetAddress[] baiduAddress2 = InetAddress.getAllByName("www.baidu.com");
System.out.println(Arrays.toString(baiduAddress2));
}
}
LAPTOP-NN58DDA7/192.168.199.153
LAPTOP-NN58DDA7
192.168.199.153
LAPTOP-NN58DDA7/192.168.199.153
/192.168.199.153
www.baidu.com/14.215.177.38
[www.baidu.com/14.215.177.38, www.baidu.com/14.215.177.39]