java ping类_Java代码ping ip工具类

packagecom.v.photos.utils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.nio.charset.Charset;/*** @Author: 孙创业

* @Date:2019/10/29 18:13*/

public classPingUtil {private static Logger logger = LoggerFactory.getLogger(PingUtil.class);/**ping ipaddress 完整返回信息*/

public static String executeLinuxCmd(String ipAddress, int pingTimes, inttimeOut) {

Runtime run=Runtime.getRuntime();

String pingCommand;try{

String osName= System.getProperty("os.name");if(osName.contains("Windows")){

pingCommand= "ping " + ipAddress + " -n " + pingTimes + " -w " +timeOut;

}else{

pingCommand= "ping " + " -c " + "4" + " -w " + "2 " +ipAddress;

}

Process process=run.exec(pingCommand);

InputStream in=process.getInputStream();

BufferedReader bs= new BufferedReader(new InputStreamReader(in, Charset.forName("GBK")));

StringBuffer out= newStringBuffer();

String content= null;while ((content = bs.readLine()) != null) {

out.append(content+ "\n");

}

in.close();

process.destroy();returnout.toString();

}catch(IOException e) {

e.printStackTrace();

}return null;

}/**ping ipaddress 完整返回true在线 false离线*/

public static boolean ping(String ipAddress, int pingTimes, inttimeOut) {

BufferedReader in= null;

String pingCommand;

Runtime r=Runtime.getRuntime();

String osName= System.getProperty("os.name");if(osName.contains("Windows")){

pingCommand= "ping " + ipAddress + " -n " + pingTimes + " -w " +timeOut;

}else{

pingCommand= "ping " + " -c " + "4" + " -w " + "2 " +ipAddress;

}try{

Process p=r.exec(pingCommand);if (p == null) {return false;

}

in= new BufferedReader(newInputStreamReader(p.getInputStream()));int connectedCount = 0;

String line;while ((line = in.readLine()) != null) {

connectedCount+=getCheckResult(line,osName);

}return connectedCount >= 2 ? true : false;

}catch(Exception ex) {

ex.printStackTrace();//出现异常则返回假

return false;

}finally{try{

in.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}private static intgetCheckResult(String line,String osName) {if(osName.contains("Windows")){if(line.contains("TTL=")){return 1;

}

}else{if(line.contains("ttl=")){return 1;

}

}return 0;

}public static voidmain(String args[]) {//String ping = executeLinuxCmd("10.3.149.27", 2, 1);

String ping = executeLinuxCmd("10.4.8.144", 2, 1);

System.out.println(ping);//boolean ping1 = ping("10.3.149.27", 2, 1);

boolean ping1 = ping("10.4.88.144", 2, 1);

System.out.println("盒子IP地址:" + "10.4.8.144" + (ping1 ? "在线" : "下线"));

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值