7

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 creating the socket, i found that the port which was used by the same thread before, is not getting released on close() of the socket. So i tried like this

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

The problem is , it is not reaching to the second line also. in the first line itself i am getting the expcetion BindException: Address already in use.

Can anyone please help me how to handle this is situation.

Is there any way to release the port ?

Thanks & Regards,
SSuman185

Suman
  • 4,221
  • 7
  • 44
  • 64

3 Answers3

16

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.

poy
  • 10,063
  • 9
  • 49
  • 74
7

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I tried this, but got a doubt? i observed that when i create DatagramSocket() with out parameters, its getting bind to some free port number. After setting the reuse address and bind, will bind to the new port. What happens to the old port? – Suman Oct 21 '11 at 06:51
  • @SSuman185 correct, well spotted. You have to create a MulticastSocket. You can use that the same as a DatagramSocket, whose default constructor got mis-designed about 15 years ago. – user207421 Oct 21 '11 at 07:26
  • @Suman I *have* explained. Construct a MulticastSocket with no arguments. What part of that don't you understand? – user207421 Oct 28 '13 at 22:18
1

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;
    }
Moti Bartov
  • 3,454
  • 33
  • 42