I have a part in code that checks port availability (opens connection and immediately close it) :
try{
new ServerSocket(currentConnector.getPort()).close();
}
The porblem here is that the port enters a state of TIME_WAIT which differs from system to system.
I want to make sure that after close()
the port is available.
One way I can think of is adding 60-90 seconds of sleep. But it doesn't seem very elegant.
Can I validate with Java (w/o bash/batch) that the port was released from TIME_WAIT?
Thanks!
The port only enters TIME-WAIT if someone has connected to it.
You can overcome the BindException
that results by:
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress(port));
However I question the objective. If you want to listen at the port, listen at it, and catch the exception then. If you want to see whether you can connect to it, connect to it, and handle the exception as it arises. The technique of trying to predict the future is just fortune-telling in the end. Unsound technique. The correct way to detect whether any resource is available for use is just to try to use it in the normal way. Anything else is liable to false negatives, false positives, and timing-window problems.