Suman Suman - 1 year ago 144
Android Question

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 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);

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,


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download