1. 程式人生 > >JAVA中Ping IP地址的兩種方法

JAVA中Ping IP地址的兩種方法

 

今天進行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();
  }