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. If the socket is already closed, then this method has no effect.
If this socket is not bound then this method will first cause the socket to be bound to an address that is assigned automatically, as if invoking the bind
method with a parameter of null
. If the remote destination to which the socket is connected does not exist, or is otherwise unreachable, and if an ICMP destination unreachable packet has been received for that address, then a subsequent call to send or receive may throw a PortUnreachableException. Note, there is no guarantee that the exception will be thrown.
If a security manager has been installed then it is invoked to check access to the remote address. Specifically, if the given address
is a multicast address
, the security manager's checkMulticast
method is invoked with the given address
. Otherwise, the security manager's checkConnect
and checkAccept
methods are invoked, with the given address
and port
, to verify that datagrams are permitted to be sent and received respectively.
Care should be taken to ensure that a connected datagram socket is not shared with untrusted code. When a socket is connected, receive
and send
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, an IllegalArgumentException
will be thrown. A socket connected to a multicast address may only be used to send packets. Datagrams in the socket's socket receive buffer , which have not been received before invoking this method, may be discarded.