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. 20162327WJH第三次实验——查找与排序2

    20162327WJH第三次实验--查找与排序2 实 验 报 告 课程:程序设计与数据结构 班级: 1623 姓名: 王旌含 学号:20162327 成绩: 指导教师:娄嘉鹏 王志强 实验日期:11月 ...

  2. python配置文件操作——configparser模块

    # -*- coding: utf-8 -*- ''' Version : Python27 Author : Spring God Date : 2012-4-26 Info : 配置文件ini所在 ...

  3. Codeforces Round #353 (Div. 2) C. Money Transfers 数学

    C. Money Transfers 题目连接: http://www.codeforces.com/contest/675/problem/C Description There are n ban ...

  4. HDU 5682 zxa and leaf 二分 树形dp

    zxa and leaf 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5682 Description zxa have an unrooted t ...

  5. vue过滤器在v2.0版本用法

    vue 1.x 的写法在  vue 2.x版本已经废除 vue 1.x 写法 <body> <div id="app"> {{message | capit ...

  6. C#高级编程9-第2章 核心C#

    C#基础 使用C#命名编译器csc.exe,编译C#程序 变量 变量一般初始化后才能使用 类型判断弱类型var,根据初始值判断类型, 变量作用域,可以访问该代码的区域 类中定义的成员变量和属性,作用在 ...

  7. Android 性能监控系列一(原理篇)

    欢迎关注微信公众号:BaronTalk,获取更多精彩好文! 一. 前言 性能问题是导致 App 用户流失的罪魁祸首之一,如果用户在使用我们 App 的时候遇到诸如页面卡顿.响应速度慢.发热严重.流量电 ...

  8. PowerDesigner导出表为Excel(转)

    打开脚本运行器Ctrl+Shift+X 导出: '*************************************************************************** ...

  9. HDU 3726 Graph and Queries (离线处理+splay tree)

    Graph and Queries Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Other ...

  10. BZOJ 1500: [NOI2005]维修数列 (splay tree)

    1500: [NOI2005]维修数列 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 4229  Solved: 1283[Submit][Status ...