首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實現 Ping 與 Telnet 連線檢測:InetAddress.isReachable 與 Socket 實戰

     編輯:Java 相關知識

一、InetAddress 常用資訊獲取

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

二、isReachable —— 類 Ping 檢測

方法簽名:

  • 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 實現 Telnet 精準檢測

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 封鎖,準確反映應用層端口可達性。

四、最佳實踐建議

  1. 優先用 Socket.connect 檢測具體服務端口(HTTP 80/443、SSH 22、DB 3306/1433)。
  2. 需大規模掃描時,配合 ExecutorService 非阻塞連線 + Future 超時控制。
  3. 生產環境建議整合 Netty 或 Apache HttpClient 的連線池與健康檢查機制。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved