今天進行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();
}
java代碼ping服務IP工具類(Windows,Linux環境)
Java實現IP是否能Ping通功能