ping某个地址判断网络是否通畅(linux与windows都可用)

发布时间 2023-04-06 11:49:58作者: CccccDi
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @ClassName PingUtils
 * @Description 解析结果
 */
@Slf4j
public class PingUtils {
    public static boolean isConnect(Process process,String flag){
        boolean connect = false;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = process.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            if (null != sb && !sb.toString().equals("")) {
                if (sb.toString().indexOf(flag) > 0) {
                    // 网络畅通
                    connect = true;
                }
            }
        } catch (IOException e) {
            log.error("ping parsing IOException:{}",e);
        }finally {
            try {
                if(is != null) {
                    is.close();
                }
                if(null != isr) {
                    isr.close();
                }
                if(null != br) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return connect;
    }


    /**
     *
     * @param ipAddress  地址
     * @param pingTimes ping的次数
     * @param timeOut 间隔时间
     *                ping -c 3 -i 1   表示发3个数据包,间隔时间1秒
     * @return
     */
    public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
        String flag = "TTL";      //windows
        Runtime r = Runtime.getRuntime();
        String osName = System.getProperty("os.name");//获取操作系统类型
        String pingCommand = "";
        if (osName.toLowerCase().contains("linux")) {
            pingCommand = "ping -c " + pingTimes +" -i " + timeOut +" "+ ipAddress;
            flag = "ttl";
        } else {
            pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut; // 将要执行的ping命令,此命令是windows格式的命令
        }
        try {   // 执行命令并获取输出
            log.info("pingCommand:{}",pingCommand);
            Process p = r.exec(pingCommand);
            if (p == null) {
                log.info("Process is null");
                return false;
            }
            return isConnect(p,flag);
        } catch (Exception ex) {
            log.error("ping error",ex);   // 出现异常则返回假
            return false;
        } finally {

        }
    }

}