InetAddress 类详解
InetAddress
类详解
一、核心作用
- 封装 IP 地址:同时支持 IPv4 和 IPv6 地址
- 域名解析:将域名转换为 IP 地址(DNS 查询)
- 地址验证:检查网络地址的有效性
- 无构造方法:通过静态工厂方法获取实例
二、核心方法
方法 | 作用描述 |
---|---|
static InetAddress getByName(String host) | 通过主机名/IP字符串获取实例(可能触发DNS查询) |
static InetAddress[] getAllByName(String host) | 获取主机的所有IP地址 |
static InetAddress getLocalHost() | 获取本地主机地址 |
String getHostName() | 获取主机名(可能触发反向DNS查询) |
String getHostAddress() | 获取IP地址字符串 |
boolean isReachable(int timeout) | 测试地址可达性(ICMP ping) |
三、基础使用示例
1. 获取单个地址
import java.net.InetAddress;
import java.net.UnknownHostException;public class InetAddressDemo {public static void main(String[] args) {try {// 通过域名获取InetAddress googleAddr = InetAddress.getByName("www.google.com");System.out.println("Google IP: " + googleAddr.getHostAddress());System.out.println("Host Name: " + googleAddr.getHostName());// 通过IP地址获取InetAddress ipAddr = InetAddress.getByName("142.250.179.196");System.out.println("Host for 142.250.179.196: " + ipAddr.getHostName());} catch (UnknownHostException e) {System.err.println("Address resolution failed: " + e.getMessage());}}
}
2. 获取所有地址(多IP场景)
// 获取某个域名的所有IP地址
try {InetAddress[] baiduAddrs = InetAddress.getAllByName("www.baidu.com");System.out.println("\nBaidu IPs:");for (InetAddress addr : baiduAddrs) {System.out.println(" - " + addr.getHostAddress());}
} catch (UnknownHostException e) {e.printStackTrace();
}
3. 获取本机地址
try {InetAddress localHost = InetAddress.getLocalHost();System.out.println("\nLocal Host:");System.out.println("Name: " + localHost.getHostName());System.out.println("IP: " + localHost.getHostAddress());
} catch (UnknownHostException e) {e.printStackTrace();
}
四、运行结果示例
Google IP: 142.250.179.196
Host Name: www.google.com
Host for 142.250.179.196: fra24s01-in-f4.1e100.netBaidu IPs:- 110.242.68.3- 110.242.68.4Local Host:
Name: My-Computer.local
IP: 192.168.1.100
五、特殊地址处理
1. 回环地址验证
InetAddress loopback = InetAddress.getByName("localhost");
System.out.println("Is loopback: " + loopback.isLoopbackAddress()); // true
2. IPv6 地址处理
InetAddress ipv6Addr = InetAddress.getByName("2001:4860:4860::8888");
System.out.println("IPv6 Address: " + ipv6Addr.getHostAddress());
3. 地址可达性测试
InetAddress target = InetAddress.getByName("www.github.com");
boolean reachable = target.isReachable(5000); // 5秒超时
System.out.println("Is reachable: " + reachable);
六、注意事项
-
DNS 查询开销:
getHostName()
可能触发反向 DNS 查询- 频繁调用需考虑性能影响
-
缓存机制:
- JVM 默认缓存 DNS 查询结果
- 缓存时间由
networkaddress.cache.ttl
属性控制
-
异常处理:
- 必须捕获
UnknownHostException
- 常见触发场景:
- 无效域名
- 无网络连接
- DNS 服务器不可达
- 必须捕获
-
IPv4/IPv6 兼容性:
- 优先使用系统默认协议栈
- 可通过 JVM 参数控制:
-Djava.net.preferIPv4Stack=true -Djava.net.preferIPv6Addresses=true
七、实际应用场景
1. 验证 IP 地址格式
public static boolean isValidIP(String ip) {try {InetAddress.getByName(ip);return true;} catch (UnknownHostException e) {return false;}
}
2. 获取本机真实 IP(非回环地址)
public static String getRealLocalIP() {try {return InetAddress.getLocalHost().getHostAddress();} catch (UnknownHostException e) {return "127.0.0.1";}
}
3. 批量地址解析
public static void resolveAddresses(List<String> hosts) {hosts.forEach(host -> {try {InetAddress[] addresses = InetAddress.getAllByName(host);System.out.println(host + " : " + Arrays.stream(addresses).map(InetAddress::getHostAddress).collect(Collectors.joining(", ")));} catch (UnknownHostException e) {System.err.println("Cannot resolve: " + host);}});
}
八、与 NetworkInterface
结合使用
import java.net.NetworkInterface;
import java.util.Enumeration;// 获取本机所有网络接口的IP地址
public static void listAllIPs() {try {Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();while (interfaces.hasMoreElements()) {NetworkInterface ni = interfaces.nextElement();Enumeration<InetAddress> addresses = ni.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress addr = addresses.nextElement();System.out.println(ni.getName() + " : " + addr.getHostAddress());}}} catch (Exception e) {e.printStackTrace();}
}
通过掌握 InetAddress
类的使用,开发者可以:
- 实现灵活的网络地址管理
- 处理域名解析与反向解析
- 进行基本的网络诊断
- 为更复杂的网络编程打下基础