码迷,mamicode.com
首页 > 其他好文 > 详细

测试网络丢包情况代码

时间:2015-03-06 16:31:17      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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"));
 }
 }

 

 

测试网络丢包情况代码

标签:

原文地址:http://www.cnblogs.com/holdon521/p/4318332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!