Last active
February 10, 2019 17:44
-
-
Save boly38/0a043df5c9a9427d867a4cd16162ac5c to your computer and use it in GitHub Desktop.
Java Simple Socket Check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.gist.it; | |
import java.net.InetSocketAddress; | |
import java.net.Socket; | |
public class NetUtils { | |
/** | |
* check if a given server is listening on a given port in the limit of timeoutMs | |
* @param serverHost server hostname (or ip) | |
* @param serverPort server port | |
* @param timeoutMs timeout in ms | |
* @param exDetails message to provide as exception details when unable to connect | |
*/ | |
public static void checkServerListening(String serverHost, int serverPort, int timeoutMs, String exDetails) { | |
try (Socket s = new Socket()) { | |
s.connect(new InetSocketAddress(serverHost, serverPort), timeoutMs); | |
} catch (Exception e) { | |
String errMsg = String.format("Can't connect to [%s:%d] (timeout was %d ms) - %s, - %s", | |
serverHost, serverPort, timeoutMs, exDetails, e.getMessage()); | |
throw new IllegalStateException(errMsg); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
related (old) questions:
https://www.geekality.net/2013/04/30/java-simple-check-to-see-if-a-server-is-listening-on-a-port/
https://stackoverflow.com/questions/9525972/add-a-timeout-when-creating-a-new-socket
maybe modern framework provide ready-to-use similar feature?