java实现ping功能

package com.lbdz.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PingUtils {
    public static void main(String[] args){
        String ipAddress = "192.168.1.88";
        System.out.println(ping(ipAddress, 5, 3000));
    }

    //检测是否ping通
    public static boolean ping(String ipAddress, int pingTimes, int timeOut){
        BufferedReader buf = null;
        try {
            String pingCommand = "ping "+ipAddress+" -n "+pingTimes+" -w "+timeOut;
            Process pro = Runtime.getRuntime().exec(pingCommand);
            buf = new BufferedReader(new InputStreamReader(pro.getInputStream(),"GBK"));
            int connectedCount = 0;
            String line = null;
            while ((line = buf.readLine()) != null){
                System.out.println(line);
                connectedCount += getCheckResult(line);
            }
            //如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
            return connectedCount == pingTimes;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }finally {
            try {
                buf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否则返回0.
    private static int getCheckResult(String line) {
        Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }
}

 

posted @ 2024-12-10 11:37  一隅桥畔  阅读(97)  评论(0)    收藏  举报