Search code examples
javasocketsnetworkingtcpdatagram

AutoBind DatagramSocket like TCP Socket in java


TCP socket in java can be used to connect to a server without binding it manually.

final Socket socket = SocketChannel.open().socket();
socket.connect(StaticData.vmAddress);
//can send receive data

But when using a DataGramSocket, there seems to be no auto-bind facility. I tried this :

DatagramSocket socketTest1 = DatagramChannel.open().socket();
socketTest1.connect(InetAddress.getByName(stunServer), stunServerPort);
socketTest1.setSoTimeout(timeout);
byte[] data = sendMH.getBytes();
DatagramPacket send = new DatagramPacket(data, data.length);
socketTest1.send(send); //got error at this point

The stacktrace :

java.net.BindException: bind failed: EINVAL (Invalid argument)
W/System.err﹕ at libcore.io.IoBridge.bind(IoBridge.java:89)
W/System.err﹕ at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:68)
W/System.err﹕ at java.net.DatagramSocket.ensureBound(DatagramSocket.java:422)
W/System.err﹕ at java.net.DatagramSocket.send(DatagramSocket.java:263)
W/System.err﹕ at java.nio.DatagramChannelImpl$DatagramSocketAdapter.send(DatagramChannelImpl.java:559)
W/System.err﹕ at reach.project.stun.test.DiscoveryTest.test1(DiscoveryTest.java:103) //(socketTest1.send(send) line)

It would be really helpful if I can rely on auto-bind in DatagramSocket as well. Is there anyway to do this ?


Solution

  • To autobind a DatagramSocket to a system-allocated port, create it with new DatagramSocket(0).