Linux/windows远程ping服务器代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

public class Test {

	public int testPing() {
		int pingUsage = 0;
		try {
			// 获取properties文件中的ip地址
			Properties p = new Properties();
			InputStream is = this.getClass().getClassLoader()
					.getResourceAsStream("com/dianping/cat/ipConfig.properties");
			p.load(is);
			String ipConfig = p.getProperty("ipConfigs");
			String[] ips = ipConfig.split(",");
			for (int i = 0; i < ips.length; i++) {
				pingUsage = ping(ips[i], 2, 5000);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return pingUsage;
	}

	/**
	 * @param ipAddress
	 *            ip地址
	 * @param pingTimes
	 *            次数(一次ping,对方返回的ping的结果的次数)
	 * @param timeOut
	 *            超时时间 单位ms(ping不通,设置的此次ping结束时间)
	 * @return
	 */
	public static int ping(String ipAddress, int pingTimes, int timeOut) {
		BufferedReader in = null;
		String pingCommand = null;
		Runtime r = Runtime.getRuntime();
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().contains("windows") || osName.toLowerCase().contains("win")) {
			// 将要执行的ping命令,此命令是windows格式的命令
			pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
		} else {
			// 将要执行的ping命令,此命令是Linux格式的命令
			// -c:次数,-w:超时时间(单位/ms) ping -c 10 -w 0.5 192.168.120.206
			pingCommand = "ping " + " -c " + pingTimes + " -w " + timeOut + " " + ipAddress;
		}
		// System.out.println("命令:" + pingCommand);
		try {
			// 执行命令并获取输出
			Process p = r.exec(pingCommand);
			if (p == null) {
				return 0;
			}
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			int connectedCount = 0;
			String line = null;
			while ((line = in.readLine()) != null) {
				connectedCount += getCheckResult(line, osName);
			}
			// 如果出现类似=23 ms ttl=64(TTL=64 Windows)这样的字样,出现的次数=测试次数则返回真
			// System.out.println("ping通设备IP的次数为:" +connectedCount);
			return connectedCount >= 2 ? 5 : 0;
		} catch (Exception ex) {
			ex.printStackTrace(); // 出现异常则返回假
			return 0;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 若line含有=18 ms ttl=64字样,说明已经ping通,返回1,否則返回0.
	private static int getCheckResult(String line, String osName) {
		if (osName.contains("Windows")) {
			if (line.contains("TTL=")) {
				return 1;
			}
		} else {
			if (line.contains("ttl=")) {
				return 1;
			}
		}
		return 0;
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值