I've recently seen the a little tutorial about Java's UDP API and I've looked at the javadocs of the DatagramSocket
and DatagramPacket
classes. The class DatagramSocket
contains several connect()
and one disconnect()
methods. But isn't UDP a protocol without connections?
What do these connect
and disconnect
methods do?
From the javadocs of DatagramSocket#connect(InetAddress address, int port):
Connects the socket to a remote address for this socket. When a socket is connected to a remote address, packets may only be sent to or received from that address. By default a datagram socket is not connected.
...
When a socket is connected,
receive
andsend
will not perform any security checks on incoming and outgoing packets, other than matching the packet's and the socket's address and port. On a send operation, if the packet's address is set and the packet's address and the socket's address do not match, anIllegalArgumentException
will be thrown. A socket connected to a multicast address may only be used to send packets.
So it's not really a way to establish a "connection" the same way TCP does, but a way to prevent sending or receiving packets to/from other addresses.