InetAddress addr = InetAddress.getByName("www.microsoft.com");
System.out.println("IP: " + addr.getHostAddress()); // 207.46.19.254
System.out.println("Host: " + addr.getHostName()); // www.microsoft.com
System.out.println("Canonical: " + addr.getCanonicalHostName()); // wwwbaytest2.microsoft.com
byte[] ip = addr.getAddress(); // 需轉無號:b>=0 ? b : 256+b
方法簽名:
boolean isReachable(int timeout)boolean isReachable(NetworkInterface netif, int ttl, int timeout)InetAddress local = InetAddress.getLocalHost();
InetAddress remote = InetAddress.getByName("www.baidu.com");
System.out.println(local.isReachable(5000)); // true
System.out.println(remote.isReachable(5000)); // false(常被防火牆攔截 ICMP/端口 7)
原理:嘗試 ICMP Echo Request 或 TCP 連接端口 7(Echo 服務),極易被防火牆封鎖,不可作為唯一存活判斷。
Socket socket = new Socket();
InetSocketAddress addr = new InetSocketAddress("bbs.sysu.edu.cn", 23); // Telnet 預設 23
try {
socket.connect(addr, 5000); // 5 秒超時
System.out.println("OK - Telnet 連線成功");
} catch (IOException e) {
System.out.println("Failed: " + e.getMessage());
} finally {
try { socket.close(); } catch (IOException ignored) {}
}
優勢:直接嘗試 TCP 三向交握,繞過 ICMP 封鎖,準確反映應用層端口可達性。
Socket.connect 檢測具體服務端口(HTTP 80/443、SSH 22、DB 3306/1433)。ExecutorService 非阻塞連線 + Future 超時控制。Netty 或 Apache HttpClient 的連線池與健康檢查機制。