我现在想做一件事情,就是想看一下某个IP能不能ping通。因为我要从里边提取数据,如果不通的话会报错。所以我能想到的就是ping通了再执行提取代码,ping不通就不提取了。ping

解决方案 »

  1.   

    public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    String line = null;
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    String ip = "220.248.81.85";
    // 自行修改上面的ip位址
    try {
    process = runtime.exec("ping " + ip);
    is = process.getInputStream();
    isr = new InputStreamReader(is);
    br = new BufferedReader(isr); while ((line = br.readLine()) != null) {
    System.out.println(line); } is.close();
    isr.close();
    br.close();
    } catch (IOException e) {
    runtime.exit(1);
    }
    }
    这样就行了
      

  2.   

    java.net.InetAddress.isReachable(int timeout);
      

  3.   

    public static boolean checkNet() throws Exception{
    BufferedReader bReader = null;
    Process process = null;
    boolean flag = false;
    try {
    String[] cmdArr = new String[] { "cmd.exe", "/C", "ping www.sina.com" };
    process = Runtime.getRuntime().exec(cmdArr);
    process.getOutputStream().close();
    bReader = new BufferedReader(new InputStreamReader(process
    .getInputStream()));
    StringBuffer sb = new StringBuffer();
    String line = null;
    while ((line = bReader.readLine()) != null) {
    logger.debug("checkNet line--->" + line);
    sb.append(line);
    }
    if(sb.indexOf("100% loss")!=-1 || sb.indexOf("100% 丢失")!=-1){
    flag = false;
    }else if(sb.indexOf(" loss")!=-1 || sb.indexOf(" 丢失")!=-1){
    flag = true;
    }
    return flag;
    } catch (Exception e) {
    throw e;
    } finally {
     try {
    if (bReader != null) {
    bReader.close();
    }
    if (process != null) {
    process.destroy();
    }
    } catch (Exception e1) {
    }
    }
    }