如题,在java中,如何判定网络是否正常,比如,指定一个ip地址,判断是否能连接上。
大家最好给出源码,因为是个新手,如果是思路,还要再找资料,等我先完成任务再消化内容 谢谢

解决方案 »

  1.   

    import java.io.*;
    import java.net.*;public class Test
    {
    public static void main(String[] args)
    {
    URL url = null;
    try {
    url = new URL("http://google.com/");
    InputStream in = url.openStream();
    System.out.println("连接正常");
    in.close();
    } catch (IOException e) {
    System.out.println("无法连接到:" + url.toString());
    }
    }
    }
      

  2.   

    谢谢CrazyGou() 的恢复.你的恢复是不是只针对 url啊,如果就是一个普通的ip地址呢?
    换成一个连通的地址,他仍然提示连接不上
      

  3.   

    public class Test
    {
    public static void main(String[] args)
    {
    String ip = "192.168.1.1";
    //ip = "google.com";
    try {
    Process p = Runtime.getRuntime().exec("cmd /c ping -n 1 " + ip);  //此处1变大可以增加精确度,但影响测试速度
    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String temp = null;
    StringBuffer strBuffer = new StringBuffer();
    while ((temp = (in.readLine())) != null)
    strBuffer.append(temp);
    //System.out.println(strBuffer);
    if (strBuffer.toString().matches(".*\\(\\d?\\d% loss\\).*")) {
    System.out.println("正常");

    else {
    System.out.println("不正常");
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
      

  4.   

    import java.net.*;
    import java.io.*;
    public class IPTest
    {
    public static void main(String[] args)throws IOException
    {
    try
    {
    InetAddress ad = InetAddress.getByName("192.168.1.119");
    boolean state = ad.isReachable(5000);//测试是否可以达到该地址
    if(state)
    System.out.println("连接成功" + ad.getHostAddress());
    else
    System.err.println("连接失败");
    }
    catch(UnknownHostException e)
    {
    System.err.println("连接失败");
    }
    }
    }实现尽最大努力试图到达主机,但防火墙和服务器配置可能阻塞请求,使其在某些特定的端口可以访问时处于不可到达状态。