Skip to content

Instantly share code, notes, and snippets.

@asvignesh
Last active August 29, 2015 14:22
Show Gist options
  • Save asvignesh/c830a8f4c94fa17d68a8 to your computer and use it in GitHub Desktop.
Save asvignesh/c830a8f4c94fa17d68a8 to your computer and use it in GitHub Desktop.
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