Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of setReuseAddress in ServerSocket?

Tags:

java

sockets

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.

like image 236
Chaitanya Avatar asked Apr 17 '14 02:04

Chaitanya


1 Answers

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.

like image 148
Koitoer Avatar answered Nov 15 '22 00:11

Koitoer