Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to check whether the particular port is in use
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* Created by Vignesh on 26-05-2015.
*/
public class PortOpenTest {
public static void main(String[] args) {
PortOpenTest portTest = new PortOpenTest();
boolean result = portTest.isPortInUse(null, 9999);
System.out.print(result);
}
private boolean isPortInUse(String host, int port) {
boolean result = false;
try {
(new Socket(host, port)).close();
result = true;
} catch (SocketException e) {
// Could not connect.
} catch (UnknownHostException e) {
// Host not found
} catch (IOException e) {
// IO exception
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment