- 使用Socket 建立Tcp连接判断远程IP或域名,端口是否可达
Boolean status = false;
Socket socket = null;
try {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(Ip, port);
try {
socket.connect(socketAddress, isTimeout);
if (socket.isConnected()) {
status = true;
}
} catch (SocketTimeoutException te) {
throw new Exception("请求连接超时");
}
} catch (IOException e) {
status = false;
} catch (Exception e) {
status = false;
} finally {
if (null != socket) {
try {
socket.close();
} catch (IOException e) {
status = false;
}
}
}
Boolean status = false;
Socket socket = null;
try {
try {
socket = new Socket(Ip, port);
socket.setSoTimeout(isTimeout);
if (socket.isConnected()) {
status = true;
}
} catch (SocketTimeoutException te) {
throw new Exception("请求连接超时");
}
} catch (IOException e) {
status = false;
} catch (Exception e) {
status = false;
} finally {
if (null != socket) {
try {
socket.close();
} catch (IOException e) {
status = false;
}
}
}
- 使用 java.net.InetAddress 的isReachable 判断IP 或域名是否可达
try {
InetAddress address = InetAddress.getByName(Ip);
address.isReachable(isTimeout);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}