工作中往往有这种情况,比如验证服务器是否可用再去做一些操作..
下面这个可以判断某个服务器能否访问,注意不需要添加端口号
/**
* 检查到指定ip的网络状态
*/
public static boolean isReachable(String targetIp) {
boolean isReachable = true;
//测试能否ping通
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(targetIp);
isReachable = inetAddress.isReachable(3000);
} catch (UnknownHostException e1) {
isReachable = false;
} catch (IOException e) {
isReachable = false;
} catch (Exception e) {
isReachable = false;
}
if (!isReachable) {
isReachable = isReachableUseCmd(targetIp);
}
return isReachable;
}
下面这段代码可以判断,某个IP和端口是否可以访问,注意是端口和IP,同时是否可以访问,如果IP能访问,但是端口不能访问,那么也会报错.
public static boolean testIpAndPort(String host, int port, int timeout) {
Socket s = new Socket();