I have a simple logic Java that checks if a port is already in use or not:
public static boolean isPortInUse(int port)
{
ServerSocket socket = null;
try {
socket = new ServerSocket(port);
socket.setReuseAddress(true);
} catch (Exception e) {
return true;
}
finally
{
if (socket != null) {
try {
socket.close();
} catch (Exception e) {
return true;
}
}
}
return false;
}
I am new to socket programming so I am not able to understand what is the use of the method "setReuseAddress"
here. I have gone through this link but I am not getting clarity the purpose of it.
This explanation is coming from TCP mechanism involving some low level socket properties and protocols, basically there is an option called SO_REUSEADDR that you define when you are creating the socket, using the method setReuseAddress() enable or disable this behavior.
The current explanation is very well defined here, take a look there. Also API have very good explanation
Just take as a configuration parameter that can be modified using that method.
Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With