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;
    
    // 开始时间
    private String startTime;

// 结束时间
    private String endTime;
    
    /**
     * 构造函数
     * @param ip
     * @param timesNum
     */
    public Pinger(String ip,int timesNum){
        this.ip=ip;
        this.timesNum=timesNum;
    }
    
    /**
     * Ping后计算响应的个数
     * @return
     * @throws Exception
     */
    public int countReply() throws Exception{
        String destIp=ip;
        int maxCount=timesNum;
        
        LineNumberReader input = null;
        try {
            startTime=DateTimeUtil.getCurrDateTime();
            
            // 根据操作系统组合命令
            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);
            } else if (osName.startsWith("Linux")) {
                return parseLinuxMsg(reponse, 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());

}
            }
            
            endTime=DateTimeUtil.getCurrDateTime();
        }
        
        return 0;
    }
    
    /**
     * ping次数和响应数相等算ping通
     * @return
     * @throws Exception
     */
    public boolean isPass() throws Exception{
        return countReply()==timesNum;
    }
    
    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 String getStartTime() {
        return startTime;
    }

public String getEndTime() {
        return endTime;
    }
    
    public static void main(String[] args) throws Exception{
        Pinger p=new Pinger("www.163.com",5);
        
        System.out.println(p.countReply());
        System.out.println(p.getStartTime());
        System.out.println(p.getEndTime());
    }
}

Pinger2的更多相关文章

  1. Kali学习笔记7:三层发现

    三层发现:发送ICMP/IP数据包探测 第一种方式: 就是很简单的Ping命令: 不过linux的ping命令和windows的ping命令不一样,它会默认不停止地发数据包 我们可以通过-c参数来设置 ...

  2. 【python】列出http://www.cnblogs.com/xiandedanteng中所有博文的标题

    代码: # 列出http://www.cnblogs.com/xiandedanteng中所有博文的标题 from bs4 import BeautifulSoup import requests u ...

  3. Node.js 网页爬虫再进阶,cheerio助力

    任务还是读取博文标题. 读取app2.js // 内置http模块,提供了http服务器和客户端功能 var http=require("http"); // cheerio模块, ...

  4. Node.js 网页瘸腿稍强点爬虫再体验

    这回爬虫走得好点了,每次正常读取文章数目总是一样的,但是有程序僵住了情况,不知什么原因. 代码如下: // 内置http模块,提供了http服务器和客户端功能 var http=require(&qu ...

  5. Node.js 网页瘸腿爬虫初体验

    延续上一篇,想把自己博客的文档标题利用Node.js的request全提取出来,于是有了下面的初哥爬虫,水平有限,这只爬虫目前还有点瘸腿,请看官你指正了. // 内置http模块,提供了http服务器 ...

随机推荐

  1. [BZOJ4700]适者(CDQ分治+DP/李超线段树)

    如果没有秒杀,就是经典的国王游戏问题,按t/a从小到大排序即可. 考虑删除两个数i<j能给答案减少的贡献:S[i]*T[i]+P[i-1]*A[i]-A[i]+S[j]*T[j]+P[j-1]* ...

  2. CF1027F Session in BSU

    link 花絮: 这场看起来打得还不错的样子……(别问我是用哪个号打的). 然后听说这题的思想被出了好多次,女生赛也出过,quailty算法,然而当时没反应过来,而且时间不多啦. 题意: 有n个人,每 ...

  3. [HDU6196]happy happy happy

    题目大意: 有一个长度为n的数列,A和B两个人轮流从两端取数,B先取,A想使分数严格小于B且尽量接近B,问两人分数之差最小是多少. 思路: 折半搜索,先预处理出长度为part的最大差最小差,再预处理出 ...

  4. Makefile-fPIC,C++静态库与动态库

    在计算机领域中,地址无关代码 (英文: position-independent code,缩写为PIC),又称地址无关可执行文件 (英文: position-independent executab ...

  5. 5、Redis中对Set类型的操作命令

    写在前面的话:读书破万卷,编码如有神 -------------------------------------------------------------------- ------------ ...

  6. 《学习OpenCv》 笔记(1)

    P1-P17 废话 可跳过 不过讲了如何搭建环境,如果你没有搭建的话,可以查看我的另外一个博文,详细讲了如何构建OpenCv的编程环境 P19 开始编写第一个代码

  7. cuda并行编程之求解ConjugateGradient(共轭梯度迭代)丢失dll解决方式

    在进行图像处理过程中,我们常常会用到梯度迭代求解大型线性方程组.今天在用cuda对神秘矩阵进行求解的时候.出现了缺少dll的情况: 报错例如以下图: watermark/2/text/aHR0cDov ...

  8. NAS(Network Attached Storage:网络附属存储)

    NAS(Network Attached Storage:网络附属存储)按字面简单说就是连接在网络上,具备资料存储功能的装置,因此也称为"网络存储器".它是一种专用数据存储服务器. ...

  9. Windows程序的打包,部署(vs项目打包vs2013)---ShinePans

    Windows 应用程序在开发完毕之后,怎样将程序打包并制作成安装程序在客户机上部署 是每一个windows应用程序开发完毕之后都必须面对的问题. 学习目标:                    部 ...

  10. C# iTextSharp 生成 PDF

    使用iTextSharp在Asp.Net中操作PDF系列文章 目录 http://www.cnblogs.com/CareySon/category/332146.html 实战 iTextSharp ...