1 package unit; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.net.InetAddress; 7 import java.util.regex.Matcher; 8 import java.util.regex.Pattern; 9 10 public class pingUtil { 11 public static boolean ping(String ipAddress) throws Exception{ 12 int timeOut=3000; 13 boolean status=InetAddress.getByName(ipAddress).isReachable(timeOut); // 当返回值是true时,说明host是可用的 14 return status; 15 } 16 17 public static void ping02(String ipAddress){ 18 String line=null; 19 20 try { 21 Process pro=Runtime.getRuntime().exec("ping "+ipAddress); 22 BufferedReader buf=new BufferedReader(new InputStreamReader(pro.getInputStream(),"utf-8")); 23 while((line=buf.readLine())!=null){ 24 System.out.println(line); 25 } 26 } catch (Exception e) { 27 System.out.println(e.getMessage()); 28 } 29 } 30 31 public static boolean ping(String ipAddress,int pingTimes,int timeOut){ 32 BufferedReader in=null; 33 Runtime r= Runtime.getRuntime(); 34 String pingCommand = "ping "+ipAddress+" -n "+pingTimes+" -w "+timeOut; 35 36 try {//执行命令并获取输出 37 System.out.println(pingCommand); 38 Process p = r.exec(pingCommand); 39 if(p==null){ 40 return false; 41 } 42 in = new BufferedReader(new InputStreamReader(p.getInputStream(),"utf-8")); 43 int connectedCount=0; 44 String line=null; 45 while((line=in.readLine())!=null){ 46 connectedCount += getCheckResult(line); 47 }//如果出现类似=20ms TTL=22这样的字符,出现的次数=测试次数 则返回真 48 return connectedCount == pingTimes; 49 } catch (Exception e) { 50 e.printStackTrace();//出现异常则返回假 51 return false; 52 }finally{ 53 try { 54 in.close(); 55 } catch (IOException e) { 56 e.printStackTrace(); 57 } 58 } 59 } 60 61 //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0. 62 private static int getCheckResult(String line){ 63 Pattern pattern=Pattern.compile("(\d+ms)(\s+)(TTL=\d+)",Pattern.CASE_INSENSITIVE); 64 Matcher matcher = pattern.matcher(line); 65 while(matcher.find()){ 66 return 1; 67 } 68 return 0; 69 } 70 71 public static void main(String[] args) throws Exception{ 72 String ipAddress="www.qq.com"; 73 // System.out.println(ping(ipAddress)); 74 ping02(ipAddress); 75 System.out.println(ping(ipAddress,5,5000)); 76 } 77 78 }