方法一:
public static boolean test1(String ip, int port) {
try (Socket ignored = new Socket(ip, port)) {
return true;
} catch (Exception e) {
return false;
}
}
方法二:稍微优雅点
public static boolean isSocketAlive(String hostName, int port) {
int timeout = 1500;
boolean isAlive = false;
SocketAddress socketAddress = new InetSocketAddress(hostName, port);
try(Socket socket = new Socket()) {
socket.connect(socketAddress, timeout);
isAlive = true;
} catch (SocketTimeoutException exception) {
System.out.println("SocketTimeoutException " + hostName + ":" + port + ". " + exception.getMessage());
} catch (IOException exception) {
System.out.println("IOException - Unable to connect to " + hostName + ":" + port + ". " + exception.getMessage());
}
return isAlive;
}