package com.fdway.tool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
*
* ping IP地址检查IP地址能否可用
*
*/
public class PingIPUtil {
public static void main(String[] args) throws IOException {
if(ping("www.fdway.com")){
System.out.print("通");
}else{
System.out.print("不通");
}
}
/**
* ping IP地址或域名
* @param ip 如:www.fdway.com
* @return 能否通讯正常
*/
public static boolean ping(String ip){
Runtime runtime = Runtime.getRuntime(); // 获取当前程序的运行进对象
Process process = null; // 声明处理类对象
String line = null; // 返回行信息
InputStream is = null; // 输入流
InputStreamReader isr = null; // 字节流
BufferedReader br = null;
boolean res = false;// 结果
try {
process = runtime.exec("ping " + ip); // PING
is = process.getInputStream(); // 实例化输入流
isr = new InputStreamReader(is,"gbk");// 把输入流转换成字节流,传入参数为了解决"gbk"中文乱码问题
br = new BufferedReader(isr);// 从字节中读取文本
while ((line = br.readLine()) != null) {
line = new String(line.getBytes("UTF-8"),"UTF-8");
if (line.contains("TTL")) {//通了
res = true;
break;
}else if(line.contains("无法访问目标主机")){//没通
res = false;
break;
}else if(line.contains("请求超时")){//有丢包,但是说明通了
res = true;
break;
}
}
is.close();
isr.close();
br.close();
} catch (IOException e) {
System.out.println(e);
runtime.exit(1);
}
return res;
}
}
本人写的工具类,拿走不谢。