Port Forwarding to Datagram Socket on a Different IP Address

In my application, I created the created datagarm socket and bound the 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 can’t do this. I followed the steps

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

but it gives

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

Any insight would be very helpful.

+6
source share
1 answer

To avoid exceptions when trying to decouple and reconfigure, you must set each socket created as reusable. To do this, you MUST create an unbound socket:

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

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

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

Here are some 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 closure = 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 (only for sockets for datagrams)

 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(); 
+7
source

Source: https://habr.com/ru/post/912742/


All Articles