wangxumin 2011-03-08 12:30
浏览 215
已采纳

java实现ping功能,是否到达地址的返回值为什么总是false?

这是测试代码:
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestPing {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String host = "www.baidu.com";
    int timeOut = 3000;
    try {
        boolean statu = InetAddress.getByName(host).isReachable(timeOut);
        System.out.println(statu);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

  • 写回答

2条回答 默认 最新

  • enet_java 2011-03-08 12:46
    关注

    换种方式实现吧,代码如下:
    [quote]

    /*
    * * 能否ping通IP地址
    *
    * @param server IP地址
    *
    * @param timeout 超时时长(毫秒)
    *
    * @return true能ping通
    */
    public static boolean pingServer(String server, int timeout)
    {
    BufferedReader in = null;
    Runtime r = Runtime.getRuntime();

        String pingCommand = "ping " + server + " -n 1 -w " + timeout;
        try
        {
            Process p = r.exec(pingCommand);
            if (p == null)
            {
                return false;
            }
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null)
            {
                if (line.startsWith("Reply from"))
                {
                    return true;
                }
            }
    
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return false;
        }
        finally
        {
            try
            {
                in.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return false;
    }
    

    [/quote]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器