import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

public class Pinger{
    // IP地址
    private String ip;
    
    // Ping次数    
    private int timesNum;
    
    /**
     * 构造函数
     * @param ip
     * @param timesNum
     */
    public Pinger(String ip,int timesNum){
        this.ip=ip;
        this.timesNum=timesNum;
    }
    
    /**
     * ping次数和响应数相等算ping通
     * @return
     * @throws Exception
     */
    public boolean isPass() throws Exception{
        String destIp=ip;
        int maxCount=timesNum;
        
        LineNumberReader input = null;
        try {
            // 根据操作系统组合命令
            String osName = System.getProperties().getProperty("os.name");
            String pingCmd = null;
            if (osName.startsWith("Windows")) {
                pingCmd = "cmd /c ping -n {0} {1}";
                pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
            } else if (osName.startsWith("Linux")) {
                pingCmd = "ping -c {0} {1}";
                pingCmd = MessageFormat.format(pingCmd, maxCount, destIp);
            } else {
                throw new Exception("not support OS");
            }
            
            // ping完得到响应
            Process process = Runtime.getRuntime().exec(pingCmd);
            InputStreamReader ir = new InputStreamReader(process
                    .getInputStream());
            input = new LineNumberReader(ir);
            String line;
            List<String> reponse = new ArrayList<String>();

while ((line = input.readLine()) != null) {
                if (!"".equals(line)) {
                    reponse.add(line);
                    // System.out.println("====:" + line);
                }
            }
            
            // 分析响应
            if (osName.startsWith("Windows")) {
                return parseWindowsMsg(reponse, maxCount)==maxCount;
            } else if (osName.startsWith("Linux")) {
                return parseLinuxMsg(reponse, maxCount)==maxCount;
            }

} catch (IOException e) {
            System.out.println("IOException   " + e.getMessage());

} finally {
            if (null != input) {
                try {
                    input.close();
                } catch (IOException ex) {
                    System.out.println("close error:" + ex.getMessage());

}
            }
        }
        
        return false;
    }
    
    private int parseWindowsMsg(List<String> reponse, int total) {
        int countTrue = 0;
        int countFalse = 0;
        for (String str : reponse) {
            if (str.startsWith("来自") || str.startsWith("Reply from")) {
                countTrue++;
            }
            if (str.startsWith("请求超时") || str.startsWith("Request timed out")) {
                countFalse++;
            }
        }
        return countTrue;
    }

private int parseLinuxMsg(List<String> reponse, int total) {
        int countTrue = 0;
        for (String str : reponse) {
            if (str.contains("bytes from") && str.contains("icmp_seq=")) {
                countTrue++;
            }
        }
        return countTrue;
    }
    
    public static void main(String[] args) throws Exception{
        Pinger p=new Pinger("123.abc.xyz.com",5);
        
        System.out.println(p.isPass());
    }
}

Pinger的更多相关文章

  1. Assignment 2: UDP Pinger[课后作业]

    Computer Networking : A Top-Down Approach 的课后作业. 要求: 基于UDP协议,实现一个Pinger工具. 服务端代码已经提供了,自己实现客户端的代码. 完整 ...

  2. Zabbix icmp pinger processes more than 75% busy

    Zabbix icmp pinger processes more than 75% busy   Zabbix server报"Zabbix icmp pinger processes m ...

  3. MongoDB使用小结:一些不常见的经验分享

    最近一年忙碌于数据处理相关的工作,跟MongoDB打交道极多,以下为实践过程中的Q&A,后续会不定期更新补充. 另有<MongoDB使用小结:一些常用操作分享>,注:本文完成时Mo ...

  4. iOS开发中获取WiFi相关信息

    iOS 开发中难免会遇到很多与网络方面的判断,这里做个汇总,大多可能是与WiFi相关的. 1.Ping域名.Ping某IP 有 时候可能会遇到ping 某个域名或者ip通不通,再做下一步操作.这里的p ...

  5. WordPress基础:让搜索引擎及时更新文章

    如果文章更新之后,想让搜索引擎也及时更新,你需要以下步骤 1.快速编辑文章时,勾选ping 2.设置->阅读,保证搜索引擎允许搜索 3.设置->撰写->添加url 通知url列表参考 ...

  6. squid源码安装下的conf文件默认值和提示

    #    WELCOME TO SQUID 3.0.STABLE26#    ----------------------------##    This is the default Squid c ...

  7. iOS Wi-Fi

    查漏补缺集是自己曾经做过相关的功能,但是重做相关功能或者重新看到相关功能的实现,感觉理解上更深刻.这一类的文章集中记录在查漏补缺集. iOS 开发中难免会遇到很多与网络方面的判断,这里做个汇总,大多可 ...

  8. Fping

    (十大特色功能) Ping是最常用的网络测试工具,ping的测试功能其实比较多,xp系统的ping有12个选项.但是,fping测试工具有25个选项,在ping的基础上增加了许多专业的功能,可用于更深 ...

  9. squid 学习笔记

    Squid学习笔记 1.安装前的配置 编译安装之前需要校正的参数主要包括File Descriptor和Mbuf Clusters. 1.File Descriptor 查看文件描述符的限制数目: u ...

随机推荐

  1. LOJ P3959 宝藏 状压dp noip

    https://www.luogu.org/problemnew/show/P3959 考场上我怎么想不出来这么写的,状压白学了. 直接按层次存因为如果某个点在前面存过了则肯定结果更优所以不用在意各点 ...

  2. Codeforces Round #489 (Div. 2)

    A. Nastya and an Array time limit per test 1 second memory limit per test 256 megabytes input standa ...

  3. disable_functions php-fpm root

    php.ini disable_functions 禁用某些函数 需要时注意打开 php-fpm 对应conf user group为root时 ERROR: [pool www] please sp ...

  4. Codeforces Round #357 (Div. 2) A. A Good Contest 水题

    A. A Good Contest 题目连接: http://www.codeforces.com/contest/681/problem/A Description Codeforces user' ...

  5. Codeforces Round #287 (Div. 2) A. Amr and Music 水题

    A. Amr and Music time limit per test 1 second memory limit per test 256 megabytes input standard inp ...

  6. IOS webView学习

    本文简单介绍下在IOS中,webView的基本用法,也顺便强化下自己的基础知识----天明少羽爬楼梯 一.加载外部HTML 显示webView 报错:NSURLSession/NSURLConnect ...

  7. 转:Windows中的命令行提示符里的Start命令执行路径包含空格时的问题

    转自:http://www.x2009.net/articles/windows-command-line-prompt-start-path-space.html 当使用Windows 中的命令行提 ...

  8. POJ 1151 Atlantis 求矩阵面积并 扫描线 具体解释

    题意: 给定n个矩阵的左下角和右上角坐标,求矩阵面积并(矩阵总是正放的,即与x轴y轴都平行) 思路: 扫描线裸题 http://www.cnblogs.com/fenshen371/p/3214092 ...

  9. 为DropDownListFor设置选中项

    在MVC中,当涉及到强类型编辑页,如果有select元素,需要根据当前Model的某个属性值,让Select的某项选中.本篇只整理思路,不涉及完整代码. □ 思路 往前台视图传的类型是List< ...

  10. [翻译] 5点建议,让iOS程序跑得更快

      [文章原地址]http://mobile.tutsplus.com/tutorials/iphone/ios-quick-tip-5-tips-to-increase-app-performanc ...