【问题标题】:Response time out when pinging an IP address in Java在 Java 中 ping IP 地址时响应超时
【发布时间】:2015-03-08 07:58:55
【问题描述】:

这是我用来 ping IPv4 地址并以毫秒为单位记录实际响应时间的方法。 不幸的是,我从来没有得到有效的回应。请求总是超时。总是返回 0。 请帮忙:)

private long pingHost(String host, int port) {
    try {                   
        Inet4Address inet4 = (Inet4Address)InetAddress.getByName(host);         
        long start = System.currentTimeMillis();
        if(inet4.isReachable(5000)){
            long end = System.currentTimeMillis();
            long total = end-start;
            System.out.println(total);
            return total;
        }   

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;

}

【问题讨论】:

标签: java ip ping inetaddress


【解决方案1】:

在 Java 中创建一个进程并在其中执行 ping 命令。众所周知,isReachable 方法不起作用

有关更多详细信息和代码示例,请参阅this 答案。

【讨论】:

    【解决方案2】:

    你试过了吗

    isReachable(NetworkInterface netif, int ttl, int timeout) 测试该地址是否可达。

    您的生存时间可能很短,因此连接永远不会到达目的地。

    【讨论】:

    • 即使有 25 跳也不会成为现实。
    【解决方案3】:

    可以使用Socket吗?像这样的:

    class PingTask implements Runnable {
    
        private int timeout;
        private Target target;// has InetSocketAddress field (getAddress()...)
    
        PingTask(Target target, int timeout) {
                this.target = target;
                this.timeout = timeout;
        }
    
        public String getHost() {
                return target.getAddress().getAddress() + ":" + target.getAddress().getPort();
        }
    
        @Override
        public void run() {
                Socket connection = new Socket();
                boolean reachable;
                long start = System.currentTimeMillis();
                try {
                        try {
                                connection.connect(target.getAddress(), timeout);
                        } finally {
                                connection.close();
                        }
                        long dur = (System.currentTimeMillis() - start);
                        System.out.printf("%5d ms %s%n", dur, target.getAddress().getHostString() );
                        reachable = true;
                } catch (Exception e) {
                        reachable = false;
                }
    
                if (!reachable) {
                        System.out.println(
                                String.format(
                                        "\t%s was UNREACHABLE",
                                        getHost()
                                )
                        );
                }
        } }
    

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多