Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rebinding a port to datagram socket on a difftent IP

In my application I hyave created a datagarm socket and binded a port say 9999 to ip 192.168.173.1 now i want to bind the port to a new ip say 192.168.173.2 but i am not able to do it Steps i followed

1 DatagramSocket s= new DatagramSocket(port,ip1);
2 s.disconnect();

s.close();

s= new DatagramSocket(port,ip2);

but this gives a

java,net,BindException :Address already in use : Cannot bind

Any insight would be very helpful.

like image 730
cornercoder Avatar asked Apr 09 '12 09:04

cornercoder


1 Answers

To avoid exceptions when trying to unbind and rebind, you would set each created socket as reusable. In order to do so, you MUST create an unbound socket:

DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(someSocketAddress);

More info: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setReuseAddress(boolean)

P.S. The timeout period that is the main reason for a BindException under such circumstances when using a TCP may not apply to UDP sockets, but the SO_REUSE should allow you to rebind instantly anyway. http://docs.oracle.com/javase/7/docs/api/java/net/DatagramSocket.html#setReuseAddress(boolean)

Here are a few examples:

final int port = 55880;

A) No reuse, no close = Address already in use

DatagramSocket s = new DatagramSocket(null);
s.bind(new InetSocketAddress("127.0.0.1", port));

s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress("localhost", port));

B) Reuse, no close = no complaints

DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress("127.0.0.1", port));

s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress("localhost", port));

C) No reuse, close = no complaints (for datagram sockets only)

DatagramSocket s = new DatagramSocket(null);
s.bind(new InetSocketAddress("127.0.0.1", port));
s.close();

s = new DatagramSocket(null);
s.bind(new InetSocketAddress("localhost", port));
s.close();
like image 69
afk5min Avatar answered Nov 14 '22 05:11

afk5min