Windows和Linux下 Java开发ping工具类

时间:2022-06-12 07:33:49
package com.test.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; public class PingUtils {public static boolean ping(String ip, int pingTimes, int timeOut) {
BufferedReader in = null;
String pingCommand = null; Runtime r = Runtime.getRuntime();
String osName = System.getProperty("os.name");
System.out.println(osName);
if(osName.contains("Windows")) {
//-n:要发送的回显请求数 -w:每次请求的超时时间
pingCommand = "ping " + ip + " -n " + pingTimes + " -w " + timeOut;
}else {
//linux下: -c是要发送的回显请求数,没有每次请求超时时间
pingCommand = "ping " + " -c " + pingTimes + " " + ip;
}
try {
Process p = r.exec(pingCommand);
if(p == null) {
return false;
}
       //ping命令使用的是GBK编码
in = new BufferedReader(new InputStreamReader(p.getInputStream(),"GBK"));
int connectCount = ;
String line = null;
while((line = in.readLine()) != null) {
connectCount += getCheckResult(line,osName);
}
System.out.println(connectCount); //只要ping通一次就说明连接成功?
return connectCount > ;
} catch(Exception e) {
e.printStackTrace();
logger.error("连接设备状态失败:" + e.getMessage());
return false;
} finally {
try {
in.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
} //若含有ttl=64字样,说明已经ping通,返回1,否則返回0.
private static int getCheckResult(String line, String osName) {
if(osName.contains("Windows")) {
if(line.contains("TTL")) {
return ;
}
}else {
if(line.contains("ttl")) {
return ;
}
}
return ;
} // public static void main(String[] args) {
// ping("127.0.0.1", 4 , 1000);
//
// } }

根据IP地址和端口号PING

package com.zit.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException; import org.apache.log4j.Logger; public class PingUtil { private static Logger logger = Logger.getLogger(PingUtil.class); public synchronized static boolean ping(String host, int port, int timeOut) {
boolean flag = false;
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host.trim(), port), timeOut);
flag = true;
} catch (UnknownHostException e) {
System.out.println(flag);
e.printStackTrace();
return false;
} catch (SocketTimeoutException e) {
System.out.println(flag);
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println(flag);
e.printStackTrace();
return false;
} catch(Exception e) {
System.out.println(flag);
e.printStackTrace();
logger.error("Connect device failed:" + e.getMessage());
return false;
} finally {
try {
if (socket != null) {
socket.close();
}
}
catch (Exception e) {
}
}
System.out.println(flag);
return flag;
} public static void main(String[] args) {
ping("10.86.31.47", , ); } }