InetAddress类
1. 相关方法
以下方法都是类的静态方法,直接调用即可
| 左边方法 | 右边描述 |
|---|---|
| getLocalHost | 获取本机 InetAddress 对象 |
| getByName | 根据指定主机名/域名获取 ip 地址对象 |
| getHostName(返回字符串) | 获取 InetAddress 对象的主机名 |
| getHostAddress(返回字符串) | 获取 InetAddress 对象的地址 |
注意:getLocalHost()方法有异常,需要捕获或者抛出
2. 代码示例
java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddress_ {
public static void main(String[] args) throws UnknownHostException {
// 获取主机名 + ip地址
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
// 获取 InetAddress 对象的主机名
String name = localHost.getHostName();
System.out.println(name);
// 获取 InetAddress 对象的ip地址
String ip = localHost.getHostAddress();
System.out.println(ip);
// 指定主机名或者域名获取 ip地址
InetAddress host1 = InetAddress.getByName("baidu.com");
System.out.println(host1);
InetAddress host2 = InetAddress.getByName("LAPTOP-E8O2B4GK");
System.out.println(host2);
}
}