Loading...

测试网络丢包情况代码

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PingIpUtils {

 public static boolean isWindowsOS() {
  boolean isWindowsOS = false;
  String osName = System.getProperty("os.name");
  if (osName.toLowerCase().indexOf("windows") > -1) {
   isWindowsOS = true;
  }
  return isWindowsOS;
 }
 public static String losePackage(String ip){
  String situation=pingIp(ip);
  if(situation!=null && situation.equals("连接异常")){
   return situation; 
  }else{
   if(situation!=null && Integer.parseInt(situation)>=3){
    return situation+"%  丢包情况严重!!!";
   }else{
    return situation+"%  正常!!!";
   }
  }
 }
 public static String pingIp(String ip){
      String line = null;
      String command = "ping -n 100 "+ip;
      String command1= "ping -c 100 "+ip;
      String lose="";
      int index=0;
  try
        {
   Process pro =null;
   BufferedReader buf=null;
      if(isWindowsOS()){
       //windows获取丢包情况
       pro=Runtime.getRuntime().exec(command);
       buf= new BufferedReader(new InputStreamReader(pro.getInputStream(),"GBK"));
       while ((line = buf.readLine()) != null){
                 if(line.contains("%")){
                  lose= line.subSequence(line.indexOf("(")+1, line.indexOf("%")).toString();
                 }
            }
    }else{
     //linux下获取丢包情况
     pro=Runtime.getRuntime().exec(command1);
     buf= new BufferedReader(new InputStreamReader(pro.getInputStream())); 
     while ((line = buf.readLine()) != null){
                if(line.contains("packet loss")){
                 Pattern p = Pattern.compile("received");
                Matcher m = p.matcher(line);
                while(m.find()){
               index=m.end();
                }
                lose= line.subSequence(index+1, line.indexOf("%")).toString().trim();
              }
        }
    }
         }catch (Exception ex){
            return "连接异常";
        }
  return lose;
 }
 public static void main(String[] args) {
  System.out.println(pingIp("40.1.32.50"));
 }
 }

 

 

posted @ 2015-03-06 15:17  微笑阳光哈*_*  阅读(990)  评论(0编辑  收藏  举报