欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java cmd判断本地网络状态及强度

程序员文章站 2022-06-10 12:19:49
...
package com.anxin.ssk.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.anxin.ssk.common.Config;

public class CommandUtil {

	private static Logger log = LoggerFactory.getLogger(CommandUtil.class);

	/**
	 * 执行cmd命令
	 * 
	 * @param command
	 * @throws IOException
	 */
	public static String executeCmd(String command) throws IOException {
		log.info("Execute command : " + command);
		Runtime runtime = Runtime.getRuntime();
		Process process = runtime.exec("cmd /c " + command);
		BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
		String line = null;
		StringBuilder build = new StringBuilder();
		while ((line = br.readLine()) != null) {
			log.info(line);
			build.append(line);
		}
		return build.toString();
	}

	/**
	 * 检测信号强度
	 * 
	 * @param command
	 * @throws IOException
	 */
	public static String checkSignalStrength() throws IOException {
		log.info("开始检测信号强度");
		String result = "未知";
		String cmdLines = executeCmd("ping " + Config.Http.SIGNAL_STRENGTH_URL);
		if (StringUtils.isNotEmpty(cmdLines)) {
			int lost = 0;
			int average = 0;

			if (cmdLines.indexOf("Packets:") >= 0) {
				lost = Integer.parseInt(cmdLines.substring(cmdLines.indexOf("Lost = ") + 7, cmdLines.lastIndexOf(" (")));
			}
			if (cmdLines.indexOf("Minimum = ") >= 0) {
				average = Integer.parseInt(cmdLines.substring(cmdLines.indexOf("Average = ") + 10, cmdLines.lastIndexOf("ms")));
			}

			log.info("丢包数:" + lost + ",平均时间:" + average + "ms!!!!!!!!");
			// 信号不好(有丢包现象)
			if (lost > 0) {
				result = "弱";
				log.info("信号不好(有丢包现象)");
			} else {
				// 没有网络
				if (average == 0) {
					result = "无";
					log.info("没有网络");

					// 信号正常(没有丢包现象)
				} else if (average > 0 && average <= 75) {
					result = "强";
					log.info("信号正常");
				} else if (average > 75 && average <= 150) {
					result = "中";
					log.info("信号比较弱");
				} else {
					result = "弱";
					log.info("信号不好");
				}
			}
		}

		return result;
	}

}