今天进行IP巡检时用到了PINGIP地址,以获取该IP址是否可用,查了一些文档后,发现了两种PING的方法,但试用后,还是发现第一种比较好用,如果在局域网内,当然,第二种更有效率: 上面上代码
// 方法一 最常用的 PING 方法
Runtime runtime =Runtime.getRuntime(); // 获取当前程序的运行进对象
Process process = null; //声明处理类对象
String line = null; //返回行信息
InputStream is = null; //输入流
InputStreamReader isr = null;// 字节流
BufferedReader br = null;
String ip = "www.baidu.com";
boolean res = false;// 结果
try {
process =runtime.exec("ping " + ip); // PING
is =process.getInputStream(); // 实例化输入流
isr = newInputStreamReader(is);// 把输入流转换成字节流
br = newBufferedReader(isr);// 从字节中读取文本
while ((line= br.readLine()) != null) {
if(line.contains("TTL")) {
res= true;
break;
}
}
is.close();
isr.close();
br.close();
if (res){
System.out.println("ping通 ...");
} else{
System.out.println("ping不通...");
}
} catch (IOException e) {
System.out.println(e);
runtime.exit(1);
}
//方法二 下面代码为 JDK1.5PING的新方法但不能用,因为 该PING请求端口为7 而大型网站会关闭不需要的端口防止入侵
InetAddress address;
try {
address =InetAddress.getByName("www.weibo.com");
System.out.println("Name:" + address.getHostName());
System.out.println("Addr:" + address.getHostAddress());
System.out.println("Reach:" + address.isReachable(3000)); //是否能通信 返回true或false
System.out.println(address.toString());
} catch (Exception e) {
e.printStackTrace();
}