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
類的使用,開發者可以:
- 實現靈活的網絡地址管理
- 處理域名解析與反向解析
- 進行基本的網絡診斷
- 為更復雜的網絡編程打下基礎