Skip to content Skip to sidebar Skip to footer

How To Set Reuse Address Option For A Datagram Socket In Java Code?

In my application there will be one thread which always be running and will be sending or listening to some port. This application runs in the background. Sometimes while creatin

Solution 1:

DatagramSocket(inetAddr) binds to the port. You need to setReuseAddress(true) BEFORE you bind.

To do this... use the following:

dc = new DatagramSocket(null);
dc.setReuseAddress(true);
dc.bind(inetAddr);

This constructor leaves the port unbound.


Solution 2:

Use a MulticastSocket. Construct it with no arguments. That implicitly calls setReuseAddress(true). Then call bind().

At the moment you are calling setReuseAddress() too late for it to do any good.


Solution 3:

This is how it worked for me:

try {
      clientMulticastSocket = new MulticastSocket(null);
      clientMulticastSocket.setReuseAddress(true);
      clientMulticastSocket.bind(new InetSocketAddress(multicastHostAddress, multicastPort));
      clientMulticastSocket.joinGroup(multicastHostAddress);
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }

Post a Comment for "How To Set Reuse Address Option For A Datagram Socket In Java Code?"