java.net.InetAddress 是 Java 處理 IP 位址與網域名稱的核心類別,封裝了 DNS 解析功能。本文詳細說明 TCP/IP 基礎、InetAddress 核心方法與實務應用範例。
| 層級 | 功能 | 關鍵協定 |
|---|---|---|
| 應用層 | 提供網路服務 | HTTP, FTP, SMTP, DNS, Telnet |
| 傳輸層 | 端到端通訊 | TCP (可靠), UDP (快速) |
| 網路層 | 路由與定址 | IP (IPv4/IPv6) |
| 網路介面層 | 實體傳輸 | Ethernet, Wi-Fi |
常見表示:點分十進制 (192.168.1.1) 或網域名稱 (www.google.com)
| 方法 | 說明 | 回傳值 |
|---|---|---|
| getByName(String host) | 根據主機名/域名取得 InetAddress | InetAddress |
| getLocalHost() | 取得本機 InetAddress | InetAddress |
| getHostName() | 取得主機名稱 | String |
| getHostAddress() | 取得 IP 位址字串 | String |
| getAllByName(String host) | 取得所有對應 IP(負載平衡常用) | InetAddress[] |
| isReachable(int timeout) | 測試主機可達性 (Ping) | boolean |
public class InetAddressDemo {
public static void main(String[] args) {
try {
// 1. 解析域名
InetAddress addr = InetAddress.getByName("www.google.com");
System.out.println("主機名: " + addr.getHostName());
System.out.println("IP 位址: " + addr.getHostAddress());
// 2. 取得本機資訊
InetAddress local = InetAddress.getLocalHost();
System.out.println("本機名: " + local.getHostName());
System.out.println("本機 IP: " + local.getHostAddress());
// 3. 多 IP 解析 (如 CDN、負載平衡)
InetAddress[] addrs = InetAddress.getAllByName("www.facebook.com");
for (InetAddress a : addrs) {
System.out.println("IP: " + a.getHostAddress());
}
} catch (UnknownHostException e) {
System.err.println("無法解析主機: " + e.getMessage());
} catch (IOException e) {
System.err.println("網路錯誤: " + e.getMessage());
}
}
}
public static boolean isHostReachable(String host, int timeoutMs) {
try {
InetAddress address = InetAddress.getByName(host);
return address.isReachable(timeoutMs);
} catch (IOException e) {
return false;
}
}
// 使用
if (isHostReachable("192.168.1.1", 3000)) {
System.out.println("主機可達");
}
InetAddress 同時支援 IPv4 (Inet4Address) 與 IPv6 (Inet6Address):
InetAddress addr = InetAddress.getByName("::1"); // IPv6 回環位址
System.out.println("類別: " + addr.getClass().getSimpleName()); // Inet6Address
System.out.println("IP: " + addr.getHostAddress()); // 0:0:0:0:0:0:0:1
結合 NetworkInterface 列舉本機所有網卡 IP:
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());
}
}
networkaddress.cache.ttl 系統屬性調整isReachable 在某些作業系統需要管理員權限