java中使用ping命令

方式一:下面的代码展示了如何在J2SE 5中使用InetAddress.isReachable方法模拟“ping”命令。

import java.io.*;
import java.net.*;

public class reachable{
 public static void main(String args[]) {
  String[] addrs= {"www.java.sun.com","www.yahoo.com","www.google.com"};
  try{
    for(int i=0;i<addrs.length;i++)
          {
          InetAddress addr=InetAddress.getByName(addrs[i]);
          System.out.println("Name:"+addr.getHostName());
          System.out.println("Addr:"+addr.getHostAddress());

          //the address will be checked for 5005 miliseconds
          System.out.println("Reach:"+addr.isReachable(5005));
          }
        }catch(UnknownHostException e){         
          System.out.println(e.getMessage());
        }catch(IOException e){
          System.err.println(e.getMessage());
      }
    }
}


方式二:

import java.io.BufferedReader;     
import java.io.IOException;     
import java.io.InputStreamReader;     
   
   
public class JavaPing{     
     
 public static void main(String[] args) {        
  try {      
   Process p = Runtime.getRuntime().exec("ping 192.168.1.86");     
   BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));      
   String line = "";      
   while ((line = br.readLine()) != null) {      
    System.out.println(line);      
   }      
   br.close();      
  } catch (IOException e) {      
      e.printStackTrace();      
  }      
    }     
}
  

你可能感兴趣的:(java,Yahoo,J2SE,Google,sun)