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

Java 模擬 Ping 操作工具類實現

     編輯:Java 相關知識

核心原理

利用 InetAddress.isReachable(timeout) 發送 ICMP 回顯請求(需 Root 權限)或 TCP 回聲協議(非 Root)探測主機可達性,統計延遲與丟包率。

工具類 SimplePing 設計亮點

  • 多線程並發探測:構造函數啟動 N 個守護線程並發執行,減少總耗時。
  • 結果聚合:線程安全統計到達次數、平均延遲、丟包率、解析 IP。
  • 阻塞等待:主線程 wait() 直到所有探測完成或超時。

關鍵代碼

public class SimplePing implements Runnable {
    private final Object lock = new Object();
    private int count, timeout, arrived;
    private float lossRate, avgDelay;
    private String host, resolvedIp;

    public SimplePing(String host, int count, int timeout) {
        this.host = host; this.count = count; this.timeout = timeout;
        for (int i = 0; i < count; i++) new Thread(this).start();
        synchronized(lock) { try { lock.wait(); } catch (InterruptedException ignored) {} }
    }

    @Override public void run() {
        long start = System.currentTimeMillis();
        boolean reachable = false;
        try {
            InetAddress addr = InetAddress.getByName(host);
            reachable = addr.isReachable(timeout);
            if (reachable) resolvedIp = addr.getHostAddress();
        } catch (IOException ignored) {}
        long delay = System.currentTimeMillis() - start;
        recordResult(reachable, delay);
    }

    private void recordResult(boolean ok, long delay) {
        synchronized(lock) {
            if (ok) { arrived++; avgDelay = (avgDelay + delay) / 2f; }
            if (--count == 0) { lossRate = 1f - arrived/(float)(count+arrived); lock.notifyAll(); }
        }
    }
    // getter 方法...
}

使用示例

SimplePing ping = new SimplePing("www.baidu.com", 4, 3000);
System.out.println("IP: " + ping.getIp());
System.out.println("丟包率: " + ping.getLossRate());
System.out.println("平均延遲: " + ping.getDelay() + "ms");
System.out.println("是否可達: " + ping.getIsSucceed());

局限性說明

  • isReachable 非 Root 環境下退化為 TCP 連接嘗試(默認端口 7),非真正 ICMP Ping,可能誤判。
  • 防火牆攔截 ICMP/TCP 會導致假性不可達。
  • 生產環境建議調用系統 ping 命令解析輸出,或使用 JNI 調用底層 ICMP。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved