Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 423
Suman Avatar asked Oct 20 '11 07:10

Suman


People also ask

What is DatagramSocket Java?

A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order.

What information is needed to create a datagram socket?

DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket and binds it with the specified port number and host address.

How what is the method for creation of the UDP datagram socket?

Creation of DatagramPacket: In this step, the packet for sending/receiving data via a datagramSocket is created. Syntax: public DatagramPacket(byte[] buf, int offset, int length, SocketAddress address) Parameters: buf - the packet data. offset - the packet data offset. length - the packet data length.


1 Answers

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.

like image 71
poy Avatar answered Oct 03 '22 09:10

poy