1 /*
   2  * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.net;
  27 
  28 import java.io.IOException;
  29 import java.io.UncheckedIOException;
  30 import java.nio.channels.DatagramChannel;
  31 import java.nio.channels.MulticastChannel;
  32 import java.security.AccessController;
  33 import java.security.PrivilegedAction;
  34 import java.util.Objects;
  35 import java.util.Set;
  36 import sun.net.NetProperties;
  37 import sun.nio.ch.DefaultSelectorProvider;
  38 
  39 /**
  40  * This class represents a socket for sending and receiving datagram packets.
  41  *
  42  * <p>A datagram socket is the sending or receiving point for a packet
  43  * delivery service. Each packet sent or received on a datagram socket
  44  * is individually addressed and routed. Multiple packets sent from
  45  * one machine to another may be routed differently, and may arrive in
  46  * any order.
  47  *
  48  * <p> Where possible, a newly constructed {@code DatagramSocket} has the
  49  * {@link StandardSocketOptions#SO_BROADCAST SO_BROADCAST} socket option enabled so as
  50  * to allow the transmission of broadcast datagrams. In order to receive
  51  * broadcast packets a DatagramSocket should be bound to the wildcard address.
  52  * In some implementations, broadcast packets may also be received when
  53  * a DatagramSocket is bound to a more specific address.
  54  * <p>
  55  * Example:
  56  * <pre>{@code
  57  *              DatagramSocket s = new DatagramSocket(null);
  58  *              s.bind(new InetSocketAddress(8888));
  59  * }</pre>
  60  * Which is equivalent to:
  61  * <pre>{@code
  62  *              DatagramSocket s = new DatagramSocket(8888);
  63  * }</pre>
  64  * Both cases will create a DatagramSocket able to receive broadcasts on
  65  * UDP port 8888.
  66  *
  67  * <p> The {@code DatagramSocket} class defines convenience
  68  * methods to set and get several socket options. This class also
  69  * defines the {@link #setOption(SocketOption,Object) setOption}
  70  * and {@link #getOption(SocketOption) getOption} methods to set
  71  * and query socket options.
  72  * A {@code DatagramSocket} supports the following socket options:
  73  * <blockquote>
  74  * <a id="SocketOptions"></a>
  75  * <table class="striped">
  76  * <caption style="display:none">Socket options</caption>
  77  * <thead>
  78  *   <tr>
  79  *     <th scope="col">Option Name</th>
  80  *     <th scope="col">Description</th>
  81  *   </tr>
  82  * </thead>
  83  * <tbody>
  84  *   <tr>
  85  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>
  86  *     <td> The size of the socket send buffer in bytes </td>
  87  *   </tr>
  88  *   <tr>
  89  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
  90  *     <td> The size of the socket receive buffer in bytes </td>
  91  *   </tr>
  92  *   <tr>
  93  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
  94  *     <td> Re-use address </td>
  95  *   </tr>
  96  *   <tr>
  97  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_BROADCAST SO_BROADCAST} </th>
  98  *     <td> Allow transmission of broadcast datagrams </td>
  99  *   </tr>
 100  *   <tr>
 101  *     <th scope="row"> {@link java.net.StandardSocketOptions#IP_TOS IP_TOS} </th>
 102  *     <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td>
 103  *   </tr>
 104  * </tbody>
 105  * </table>
 106  * </blockquote>
 107  * <p> In addition, the {@code DatagramSocket} class defines methods to {@linkplain
 108  * #joinGroup(SocketAddress, NetworkInterface) join} and {@linkplain
 109  * #leaveGroup(SocketAddress, NetworkInterface) leave} a multicast group, and
 110  * supports <a href="DatagramSocket.html#MulticastOptions">multicast options</a> which
 111  * are useful when {@linkplain #joinGroup(SocketAddress, NetworkInterface) joining},
 112  * {@linkplain #leaveGroup(SocketAddress, NetworkInterface) leaving}, or sending datagrams
 113  * to a multicast group.
 114  * The following multicast options are supported:
 115  * <blockquote>
 116  * <a id="MulticastOptions"></a>
 117  * <table class="striped">
 118  * <caption style="display:none">Multicast options</caption>
 119  * <thead>
 120  *   <tr>
 121  *     <th scope="col">Option Name</th>
 122  *     <th scope="col">Description</th>
 123  *   </tr>
 124  * </thead>
 125  * <tbody>
 126  *   <tr>
 127  *     <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_IF IP_MULTICAST_IF} </th>
 128  *     <td> The network interface for Internet Protocol (IP) multicast datagrams </td>
 129  *   </tr>
 130  *   <tr>
 131  *     <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_TTL
 132  *       IP_MULTICAST_TTL} </th>
 133  *     <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast
 134  *       datagrams </td>
 135  *   </tr>
 136  *   <tr>
 137  *     <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP
 138  *       IP_MULTICAST_LOOP} </th>
 139  *     <td> Loopback for Internet Protocol (IP) multicast datagrams </td>
 140  *   </tr>
 141  * </tbody>
 142  * </table>
 143  * </blockquote>
 144  * An implementation may also support additional options.
 145  *
 146  * @apiNote  <a id="Multicasting"></a><b>Multicasting with DatagramSocket</b>
 147  *
 148  * <p> {@link DatagramChannel} implements the {@link MulticastChannel} interface
 149  * and provides an alternative API for sending and receiving multicast datagrams.
 150  * The {@link MulticastChannel} API supports both {@linkplain
 151  * MulticastChannel#join(InetAddress, NetworkInterface) any-source} and
 152  * {@linkplain MulticastChannel#join(InetAddress, NetworkInterface, InetAddress)
 153  * source-specific} multicast. Consider using {@code DatagramChannel} for
 154  * multicasting.
 155  *
 156  * <p> {@code DatagramSocket} can be used directly for multicasting. However,
 157  * contrarily to {@link MulticastSocket}, {@code DatagramSocket} doesn't call the
 158  * {@link DatagramSocket#setReuseAddress(boolean)} method to enable the SO_REUSEADDR
 159  * socket option by default. If creating a {@code DatagramSocket} intended to
 160  * later join a multicast group, the caller should consider explicitly enabling
 161  * the SO_REUSEADDR option.
 162  *
 163  * <p> An instance of {@code DatagramSocket} can be used to send or
 164  * receive multicast datagram packets. It is not necessary to join a multicast
 165  * group in order to send multicast datagrams. Before sending out multicast
 166  * datagram packets however, the default outgoing interface for sending
 167  * multicast datagram should first be configured using
 168  * {@link #setOption(SocketOption, Object) setOption} and
 169  * {@link StandardSocketOptions#IP_MULTICAST_IF}:
 170  *
 171  * <pre>{@code
 172  *    DatagramSocket sender = new DatagramSocket(new InetSocketAddress(0));
 173  *    NetworkInterface outgoingIf = NetworkInterface.getByName("en0");
 174  *    sender.setOption(StandardSocketOptions.IP_MULTICAST_IF, outgoingIf);
 175  *
 176  *    // optionally configure multicast TTL; the TTL defines the scope of a
 177  *    // multicast datagram, for example, confining it to host local (0) or
 178  *    // link local (1) etc...
 179  *    int ttl = ...; // a number betwen 0 and 255
 180  *    sender.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
 181  *
 182  *    // send a packet to a multicast group
 183  *    byte[] msgBytes = ...;
 184  *    InetAddress mcastaddr = InetAddress.getByName("228.5.6.7");
 185  *    int port = 6789;
 186  *    InetSocketAddress dest = new InetSocketAddress(mcastaddr, port);
 187  *    DatagramPacket hi = new DatagramPacket(msgBytes, msgBytes.length, dest);
 188  *    sender.send(hi);
 189  * }</pre>
 190  *
 191  * <p> An instance of {@code DatagramSocket} can also be used to receive
 192  * multicast datagram packets. A {@code DatagramSocket} that is created
 193  * with the intent of receiving multicast datagrams should be created
 194  * <i>unbound</i>. Before binding the socket, {@link #setReuseAddress(boolean)
 195  * setReuseAddress(true)} should be configured:
 196  *
 197  * <pre>{@code
 198  *    DatagramSocket socket = new DatagramSocket(null); // unbound
 199  *    socket.setReuseAddress(true); // set reuse address before binding
 200  *    socket.bind(new InetSocketAddress(6789)); // bind
 201  *
 202  *    // joinGroup 228.5.6.7
 203  *    InetAddress mcastaddr = InetAddress.getByName("228.5.6.7");
 204  *    InetSocketAddress group = new InetSocketAddress(mcastaddr, 0);
 205  *    NetworkInterface netIf = NetworkInterface.getByName("en0");
 206  *    socket.joinGroup(group, netIf);
 207  *    byte[] msgBytes = new byte[1024]; // up to 1024 bytes
 208  *    DatagramPacket packet = new DatagramPacket(msgBytes, msgBytes.length);
 209  *    socket.receive(packet);
 210  *    ....
 211  *    // eventually leave group
 212  *    socket.leaveGroup(group, netIf);
 213  * }</pre>
 214  *
 215  * <p><a id="PlatformDependencies"></a><b>Platform dependencies</b>
 216  * <p>The multicast implementation is intended to map directly to the native
 217  * multicasting facility. Consequently, the following items should be considered
 218  * when developing an application that receives IP multicast datagrams:
 219  * <ol>
 220  *    <li> Contrarily to {@link DatagramChannel}, the constructors of {@code DatagramSocket}
 221  *        do not allow to specify the {@link ProtocolFamily} of the underlying socket.
 222  *        Consequently, the protocol family of the underlying socket may not
 223  *        correspond to the protocol family of the multicast groups that
 224  *        the {@code DatagramSocket} will attempt to join.
 225  *        <br>
 226  *        There is no guarantee that a {@code DatagramSocket} with an underlying
 227  *        socket created in one protocol family can join and receive multicast
 228  *        datagrams when the address of the multicast group corresponds to
 229  *        another protocol family. For example, it is implementation specific if a
 230  *        {@code DatagramSocket} to an IPv6 socket can join an IPv4 multicast group
 231  *        and receive multicast datagrams sent to the group.
 232  *    </li>
 233  *    <li> Before joining a multicast group, the {@code DatagramSocket} should be
 234  *        bound to the wildcard address.
 235  *        If the socket is bound to a specific address, rather than the wildcard address
 236  *        then it is implementation specific if multicast datagrams are received
 237  *        by the socket.
 238  *    </li>
 239  *    <li> The SO_REUSEADDR option should be enabled prior to binding the socket.
 240  *        This is required to allow multiple members of the group to bind to the same address.
 241  *    </li>
 242  * </ol>
 243  *
 244  * @author  Pavani Diwanji
 245  * @see     java.net.DatagramPacket
 246  * @see     java.nio.channels.DatagramChannel
 247  * @since 1.0
 248  */
 249 public class DatagramSocket implements java.io.Closeable {
 250 
 251     // An instance of DatagramSocketAdaptor, NetMulticastSocket, or null
 252     private final DatagramSocket delegate;
 253 
 254     DatagramSocket delegate() {
 255         if (delegate == null) {
 256             throw new InternalError("Should not get here");
 257         }
 258         return delegate;
 259     }
 260 
 261     /**
 262      * All constructors eventually call this one.
 263      * @param delegate The wrapped DatagramSocket implementation, or null.
 264      */
 265     DatagramSocket(DatagramSocket delegate) {
 266         assert delegate == null
 267                 || delegate instanceof NetMulticastSocket
 268                 || delegate instanceof sun.nio.ch.DatagramSocketAdaptor;
 269         this.delegate = delegate;
 270     }
 271 
 272     /**
 273      * Constructs a datagram socket and binds it to any available port
 274      * on the local host machine.  The socket will be bound to the
 275      * {@link InetAddress#isAnyLocalAddress wildcard} address.
 276      *
 277      * <p>If there is a security manager,
 278      * its {@code checkListen} method is first called
 279      * with 0 as its argument to ensure the operation is allowed.
 280      * This could result in a SecurityException.
 281      *
 282      * @throws     SocketException  if the socket could not be opened,
 283      *              or the socket could not be bound.
 284      * @throws     SecurityException  if a security manager exists and its
 285      *             {@code checkListen} method doesn't allow the operation.
 286      *
 287      * @see SecurityManager#checkListen
 288      */
 289     public DatagramSocket() throws SocketException {
 290         this(new InetSocketAddress(0));
 291     }
 292 
 293     /**
 294      * Creates an unbound datagram socket with the specified
 295      * DatagramSocketImpl.
 296      *
 297      * @param impl an instance of a <B>DatagramSocketImpl</B>
 298      *        the subclass wishes to use on the DatagramSocket.
 299      * @since   1.4
 300      */
 301     protected DatagramSocket(DatagramSocketImpl impl) {
 302         this(new NetMulticastSocket(impl));
 303     }
 304 
 305     /**
 306      * Creates a datagram socket, bound to the specified local
 307      * socket address.
 308      * <p>
 309      * If the address is {@code null} an unbound socket will be created.
 310      *
 311      * <p>If there is a security manager,
 312      * its {@code checkListen} method is first called
 313      * with the port from the socket address
 314      * as its argument to ensure the operation is allowed.
 315      * This could result in a SecurityException.
 316      *
 317      * @param bindaddr local socket address to bind, or {@code null}
 318      *                 for an unbound socket.
 319      *
 320      * @throws     SocketException  if the socket could not be opened,
 321      *               or the socket could not bind to the specified local port.
 322      * @throws     SecurityException  if a security manager exists and its
 323      *             {@code checkListen} method doesn't allow the operation.
 324      * @throws     IllegalArgumentException  if bindaddr is a
 325      *              SocketAddress subclass not supported by this socket.
 326      *
 327      * @see SecurityManager#checkListen
 328      * @since   1.4
 329      */
 330     public DatagramSocket(SocketAddress bindaddr) throws SocketException {
 331         this(createDelegate(bindaddr, DatagramSocket.class));
 332     }
 333 
 334     /**
 335      * Constructs a datagram socket and binds it to the specified port
 336      * on the local host machine.  The socket will be bound to the
 337      * {@link InetAddress#isAnyLocalAddress wildcard} address.
 338      *
 339      * <p>If there is a security manager,
 340      * its {@code checkListen} method is first called
 341      * with the {@code port} argument
 342      * as its argument to ensure the operation is allowed.
 343      * This could result in a SecurityException.
 344      *
 345      * @param      port local port to use in the bind operation.
 346      * @throws     SocketException  if the socket could not be opened,
 347      *               or the socket could not bind to the specified local port.
 348      * @throws     SecurityException  if a security manager exists and its
 349      *             {@code checkListen} method doesn't allow the operation.
 350      * @throws     IllegalArgumentException  if port is <a href="#PortRange">
 351      *              out of range.</a>
 352      *
 353      * @see SecurityManager#checkListen
 354      */
 355     public DatagramSocket(int port) throws SocketException {
 356         this(port, null);
 357     }
 358 
 359     /**
 360      * Creates a datagram socket, bound to the specified local
 361      * address.
 362      * <p><a id="PortRange"></a>The local port must be between 0 and
 363      * 65535 inclusive. A port number of {@code zero} will let the system pick
 364      * up an ephemeral port in a {@code bind} operation.
 365      * <p>
 366      * If the IP address is a {@link InetAddress#isAnyLocalAddress wildcard}
 367      * address, or is {@code null}, the socket will be bound to the wildcard
 368      * address.
 369      *
 370      * <p>If there is a security manager,
 371      * its {@code checkListen} method is first called
 372      * with the {@code port} argument
 373      * as its argument to ensure the operation is allowed.
 374      * This could result in a SecurityException.
 375      *
 376      * @param port local port to use in the bind operation.
 377      * @param laddr local address to bind (can be {@code null})
 378      *
 379      * @throws     SocketException  if the socket could not be opened,
 380      *               or the socket could not bind to the specified local port.
 381      * @throws     SecurityException  if a security manager exists and its
 382      *             {@code checkListen} method doesn't allow the operation.
 383      * @throws     IllegalArgumentException  if port is <a href="#PortRange">
 384      *              out of range.</a>
 385      *
 386      * @see SecurityManager#checkListen
 387      * @since   1.1
 388      */
 389     public DatagramSocket(int port, InetAddress laddr) throws SocketException {
 390         this(new InetSocketAddress(laddr, port));
 391     }
 392 
 393     /**
 394      * Binds this DatagramSocket to a specific address and port.
 395      * <p>
 396      * If the address is {@code null}, then the system will pick up
 397      * an ephemeral port and a valid local address to bind the socket.
 398      *
 399      * @param   addr The address and port to bind to.
 400      * @throws  SocketException if any error happens during the bind, or if the
 401      *          socket is already bound.
 402      * @throws  SecurityException  if a security manager exists and its
 403      *             {@code checkListen} method doesn't allow the operation.
 404      * @throws IllegalArgumentException if addr is a SocketAddress subclass
 405      *         not supported by this socket.
 406      * @since 1.4
 407      */
 408     public void bind(SocketAddress addr) throws SocketException {
 409         delegate().bind(addr);
 410     }
 411 
 412     /**
 413      * Connects the socket to a remote address for this socket. When a
 414      * socket is connected to a remote address, packets may only be
 415      * sent to or received from that address. By default a datagram
 416      * socket is not connected. If the socket is already closed,
 417      * then this method has no effect.
 418      *
 419      * <p> If this socket is not bound then this method will first cause the
 420      * socket to be bound to an address that is assigned automatically,
 421      * as if invoking the {@link #bind bind} method with a parameter of
 422      * {@code null}. If the remote destination to which the socket is connected
 423      * does not exist, or is otherwise unreachable, and if an ICMP destination
 424      * unreachable packet has been received for that address, then a subsequent
 425      * call to send or receive may throw a PortUnreachableException. Note,
 426      * there is no guarantee that the exception will be thrown.
 427      *
 428      * <p> If a security manager has been installed then it is invoked to check
 429      * access to the remote address. Specifically, if the given {@code address}
 430      * is a {@link InetAddress#isMulticastAddress multicast address},
 431      * the security manager's {@link
 432      * java.lang.SecurityManager#checkMulticast(InetAddress)
 433      * checkMulticast} method is invoked with the given {@code address}.
 434      * Otherwise, the security manager's {@link
 435      * java.lang.SecurityManager#checkConnect(String,int) checkConnect}
 436      * and {@link java.lang.SecurityManager#checkAccept checkAccept} methods
 437      * are invoked, with the given {@code address} and {@code port}, to
 438      * verify that datagrams are permitted to be sent and received
 439      * respectively.
 440      *
 441      * <p> Care should be taken to ensure that a connected datagram socket
 442      * is not shared with untrusted code. When a socket is connected,
 443      * {@link #receive receive} and {@link #send send} <b>will not perform
 444      * any security checks</b> on incoming and outgoing packets, other than
 445      * matching the packet's and the socket's address and port. On a send
 446      * operation, if the packet's address is set and the packet's address
 447      * and the socket's address do not match, an {@code IllegalArgumentException}
 448      * will be thrown. A socket connected to a multicast address may only
 449      * be used to send packets. Datagrams in the socket's {@linkplain
 450      * java.net.StandardSocketOptions#SO_RCVBUF socket receive buffer}, which
 451      * have not been {@linkplain #receive(DatagramPacket) received} before invoking
 452      * this method, may be discarded.
 453      *
 454      * @param address the remote address for the socket
 455      *
 456      * @param port the remote port for the socket.
 457      *
 458      * @throws IllegalArgumentException
 459      *         if the address is null, or the port is <a href="#PortRange">
 460      *         out of range.</a>
 461      *
 462      * @throws SecurityException
 463      *         if a security manager has been installed and it does
 464      *         not permit access to the given remote address
 465      *
 466      * @throws UncheckedIOException
 467      *         may be thrown if connect fails, for example, if the
 468      *         destination address is non-routable
 469      *
 470      * @see #disconnect
 471      *
 472      * @since 1.2
 473      */
 474     public void connect(InetAddress address, int port) {
 475         delegate().connect(address, port);
 476     }
 477 
 478     /**
 479      * Connects this socket to a remote socket address (IP address + port number).
 480      *
 481      * <p> If given an {@link InetSocketAddress InetSocketAddress}, this method
 482      * behaves as if invoking {@link #connect(InetAddress,int) connect(InetAddress,int)}
 483      * with the given socket addresses IP address and port number, except that the
 484      * {@code SocketException} that may be raised is not wrapped in an
 485      * {@code UncheckedIOException}. Datagrams in the socket's {@linkplain
 486      * java.net.StandardSocketOptions#SO_RCVBUF socket receive buffer}, which
 487      * have not been {@linkplain #receive(DatagramPacket) received} before invoking
 488      * this method, may be discarded.
 489      *
 490      * @param   addr    The remote address.
 491      *
 492      * @throws  SocketException
 493      *          if the connect fails
 494      *
 495      * @throws IllegalArgumentException
 496      *         if {@code addr} is {@code null}, or {@code addr} is a SocketAddress
 497      *         subclass not supported by this socket
 498      *
 499      * @throws SecurityException
 500      *         if a security manager has been installed and it does
 501      *         not permit access to the given remote address
 502      *
 503      * @since 1.4
 504      */
 505     public void connect(SocketAddress addr) throws SocketException {
 506         delegate().connect(addr);
 507     }
 508 
 509     /**
 510      * Disconnects the socket. If the socket is closed or not connected,
 511      * then this method has no effect.
 512      *
 513      * @apiNote If this method throws an UncheckedIOException, the socket
 514      *          may be left in an unspecified state. It is strongly
 515      *          recommended that the socket be closed when disconnect
 516      *          fails.
 517      *
 518      * @throws  UncheckedIOException
 519      *          may be thrown if disconnect fails to dissolve the
 520      *          association and restore the socket to a consistent state.
 521      *
 522      * @see #connect
 523      *
 524      * @since 1.2
 525      */
 526     public void disconnect() {
 527         delegate().disconnect();
 528     }
 529 
 530     /**
 531      * Returns the binding state of the socket.
 532      * <p>
 533      * If the socket was bound prior to being {@link #close closed},
 534      * then this method will continue to return {@code true}
 535      * after the socket is closed.
 536      *
 537      * @return true if the socket successfully bound to an address
 538      * @since 1.4
 539      */
 540     public boolean isBound() {
 541         return delegate().isBound();
 542     }
 543 
 544     /**
 545      * Returns the connection state of the socket.
 546      * <p>
 547      * If the socket was connected prior to being {@link #close closed},
 548      * then this method will continue to return {@code true}
 549      * after the socket is closed.
 550      *
 551      * @return true if the socket successfully connected to a server
 552      * @since 1.4
 553      */
 554     public boolean isConnected() {
 555         return delegate().isConnected();
 556     }
 557 
 558     /**
 559      * Returns the address to which this socket is connected. Returns
 560      * {@code null} if the socket is not connected.
 561      * <p>
 562      * If the socket was connected prior to being {@link #close closed},
 563      * then this method will continue to return the connected address
 564      * after the socket is closed.
 565      *
 566      * @return the address to which this socket is connected.
 567      * @since 1.2
 568      */
 569     public InetAddress getInetAddress() {
 570         return delegate().getInetAddress();
 571     }
 572 
 573     /**
 574      * Returns the port number to which this socket is connected.
 575      * Returns {@code -1} if the socket is not connected.
 576      * <p>
 577      * If the socket was connected prior to being {@link #close closed},
 578      * then this method will continue to return the connected port number
 579      * after the socket is closed.
 580      *
 581      * @return the port number to which this socket is connected.
 582      * @since 1.2
 583      */
 584     public int getPort() {
 585         return delegate().getPort();
 586     }
 587 
 588     /**
 589      * Returns the address of the endpoint this socket is connected to, or
 590      * {@code null} if it is unconnected.
 591      * <p>
 592      * If the socket was connected prior to being {@link #close closed},
 593      * then this method will continue to return the connected address
 594      * after the socket is closed.
 595      *
 596      * @return a {@code SocketAddress} representing the remote
 597      *         endpoint of this socket, or {@code null} if it is
 598      *         not connected yet.
 599      * @see #getInetAddress()
 600      * @see #getPort()
 601      * @see #connect(SocketAddress)
 602      * @since 1.4
 603      */
 604     public SocketAddress getRemoteSocketAddress() {
 605         return delegate().getRemoteSocketAddress();
 606     }
 607 
 608     /**
 609      * Returns the address of the endpoint this socket is bound to.
 610      *
 611      * @return a {@code SocketAddress} representing the local endpoint of this
 612      *         socket, or {@code null} if it is closed or not bound yet.
 613      * @see #getLocalAddress()
 614      * @see #getLocalPort()
 615      * @see #bind(SocketAddress)
 616      * @since 1.4
 617      */
 618     public SocketAddress getLocalSocketAddress() {
 619         return delegate().getLocalSocketAddress();
 620     }
 621 
 622     /**
 623      * Sends a datagram packet from this socket. The
 624      * {@code DatagramPacket} includes information indicating the
 625      * data to be sent, its length, the IP address of the remote host,
 626      * and the port number on the remote host.
 627      *
 628      * <p>If there is a security manager, and the socket is not currently
 629      * connected to a remote address, this method first performs some
 630      * security checks. First, if {@code p.getAddress().isMulticastAddress()}
 631      * is true, this method calls the
 632      * security manager's {@code checkMulticast} method
 633      * with {@code p.getAddress()} as its argument.
 634      * If the evaluation of that expression is false,
 635      * this method instead calls the security manager's
 636      * {@code checkConnect} method with arguments
 637      * {@code p.getAddress().getHostAddress()} and
 638      * {@code p.getPort()}. Each call to a security manager method
 639      * could result in a SecurityException if the operation is not allowed.
 640      *
 641      * @param      p   the {@code DatagramPacket} to be sent.
 642      *
 643      * @throws     IOException  if an I/O error occurs.
 644      * @throws     SecurityException  if a security manager exists and its
 645      *             {@code checkMulticast} or {@code checkConnect}
 646      *             method doesn't allow the send.
 647      * @throws     PortUnreachableException may be thrown if the socket is connected
 648      *             to a currently unreachable destination. Note, there is no
 649      *             guarantee that the exception will be thrown.
 650      * @throws     java.nio.channels.IllegalBlockingModeException
 651      *             if this socket has an associated channel,
 652      *             and the channel is in non-blocking mode.
 653      * @throws     IllegalArgumentException if the socket is connected,
 654      *             and connected address and packet address differ, or
 655      *             if the socket is not connected and the packet address
 656      *             is not set or if its port is <a href="#PortRange">out of
 657      *             range.</a>
 658      *
 659      * @see        java.net.DatagramPacket
 660      * @see        SecurityManager#checkMulticast(InetAddress)
 661      * @see        SecurityManager#checkConnect
 662      * @revised 1.4
 663      */
 664     public void send(DatagramPacket p) throws IOException  {
 665         delegate().send(p);
 666     }
 667 
 668     /**
 669      * Receives a datagram packet from this socket. When this method
 670      * returns, the {@code DatagramPacket}'s buffer is filled with
 671      * the data received. The datagram packet also contains the sender's
 672      * IP address, and the port number on the sender's machine.
 673      * <p>
 674      * This method blocks until a datagram is received.
 675      * For the system-default socket implementation at least, if a
 676      * {@linkplain Thread#isVirtual() virtual thread} blocked in {@code receive}
 677      * is {@linkplain Thread#interrupt() interrupted} then the socket is closed
 678      * and {@link SocketException} is thrown with the interrupt status set.
 679      * <p>
 680      * The {@code length} field of the datagram packet object contains
 681      * the length of the received message. If the message is longer than
 682      * the packet's length, the message is truncated.
 683      * <p>
 684      * If there is a security manager, and the socket is not currently
 685      * connected to a remote address, a packet cannot be received if the
 686      * security manager's {@code checkAccept} method does not allow it.
 687      * Datagrams that are not permitted by the security manager are silently
 688      * discarded.
 689      *
 690      * @param      p   the {@code DatagramPacket} into which to place
 691      *                 the incoming data.
 692      * @throws     IOException  if an I/O error occurs.
 693      * @throws     SocketTimeoutException  if setSoTimeout was previously called
 694      *                 and the timeout has expired.
 695      * @throws     PortUnreachableException may be thrown if the socket is connected
 696      *             to a currently unreachable destination. Note, there is no guarantee that the
 697      *             exception will be thrown.
 698      * @throws     java.nio.channels.IllegalBlockingModeException
 699      *             if this socket has an associated channel,
 700      *             and the channel is in non-blocking mode.
 701      * @see        java.net.DatagramPacket
 702      * @see        java.net.DatagramSocket
 703      * @revised 1.4
 704      */
 705     public void receive(DatagramPacket p) throws IOException {
 706         delegate().receive(p);
 707     }
 708 
 709     /**
 710      * Gets the local address to which the socket is bound.
 711      *
 712      * <p>If there is a security manager, its
 713      * {@code checkConnect} method is first called
 714      * with the host address and {@code -1}
 715      * as its arguments to see if the operation is allowed.
 716      *
 717      * @see SecurityManager#checkConnect
 718      * @return  the local address to which the socket is bound,
 719      *          {@code null} if the socket is closed, or
 720      *          an {@code InetAddress} representing
 721      *          {@link InetAddress#isAnyLocalAddress wildcard}
 722      *          address if either the socket is not bound, or
 723      *          the security manager {@code checkConnect}
 724      *          method does not allow the operation
 725      * @since   1.1
 726      */
 727     public InetAddress getLocalAddress() {
 728         return delegate().getLocalAddress();
 729     }
 730 
 731     /**
 732      * Returns the port number on the local host to which this socket
 733      * is bound.
 734      *
 735      * @return  the port number on the local host to which this socket is bound,
 736      *          {@code -1} if the socket is closed, or
 737      *          {@code 0} if it is not bound yet.
 738      */
 739     public int getLocalPort() {
 740         return delegate().getLocalPort();
 741     }
 742 
 743     /**
 744      * Enable/disable SO_TIMEOUT with the specified timeout, in
 745      * milliseconds. With this option set to a positive timeout value,
 746      * a call to receive() for this DatagramSocket
 747      * will block for only this amount of time.  If the timeout expires,
 748      * a <B>java.net.SocketTimeoutException</B> is raised, though the
 749      * DatagramSocket is still valid. A timeout of zero is interpreted
 750      * as an infinite timeout.
 751      * The option <B>must</B> be enabled prior to entering the blocking
 752      * operation to have effect.
 753      *
 754      * @param timeout the specified timeout in milliseconds.
 755      * @throws SocketException if there is an error in the underlying protocol, such as an UDP error.
 756      * @throws IllegalArgumentException if {@code timeout} is negative
 757      * @since   1.1
 758      * @see #getSoTimeout()
 759      */
 760     public void setSoTimeout(int timeout) throws SocketException {
 761         delegate().setSoTimeout(timeout);
 762     }
 763 
 764     /**
 765      * Retrieve setting for SO_TIMEOUT.  0 returns implies that the
 766      * option is disabled (i.e., timeout of infinity).
 767      *
 768      * @return the setting for SO_TIMEOUT
 769      * @throws SocketException if there is an error in the underlying protocol, such as an UDP error.
 770      * @since   1.1
 771      * @see #setSoTimeout(int)
 772      */
 773     public int getSoTimeout() throws SocketException {
 774         return delegate().getSoTimeout();
 775     }
 776 
 777     /**
 778      * Sets the SO_SNDBUF option to the specified value for this
 779      * {@code DatagramSocket}. The SO_SNDBUF option is used by the
 780      * network implementation as a hint to size the underlying
 781      * network I/O buffers. The SO_SNDBUF setting may also be used
 782      * by the network implementation to determine the maximum size
 783      * of the packet that can be sent on this socket.
 784      * <p>
 785      * As SO_SNDBUF is a hint, applications that want to verify
 786      * what size the buffer is should call {@link #getSendBufferSize()}.
 787      * <p>
 788      * Increasing the buffer size may allow multiple outgoing packets
 789      * to be queued by the network implementation when the send rate
 790      * is high.
 791      * <p>
 792      * Note: If {@link #send(DatagramPacket)} is used to send a
 793      * {@code DatagramPacket} that is larger than the setting
 794      * of SO_SNDBUF then it is implementation specific if the
 795      * packet is sent or discarded.
 796      *
 797      * @apiNote
 798      * If {@code size > 0}, this method is equivalent to calling
 799      * {@link #setOption(SocketOption, Object)
 800      * setOption(StandardSocketOptions.SO_SNDBUF, size)}.
 801      *
 802      * @param size the size to which to set the send buffer
 803      * size, in bytes. This value must be greater than 0.
 804      *
 805      * @throws    SocketException if there is an error
 806      * in the underlying protocol, such as an UDP error.
 807      * @throws    IllegalArgumentException if the value is 0 or is
 808      * negative.
 809      * @see #getSendBufferSize()
 810      * @see StandardSocketOptions#SO_SNDBUF
 811      * @since 1.2
 812      */
 813     public void setSendBufferSize(int size) throws SocketException {
 814         delegate().setSendBufferSize(size);
 815     }
 816 
 817     /**
 818      * Get value of the SO_SNDBUF option for this {@code DatagramSocket}, that is the
 819      * buffer size, in bytes, used by the platform for output on this {@code DatagramSocket}.
 820      *
 821      * @apiNote
 822      * This method is equivalent to calling {@link #getOption(SocketOption)
 823      * getOption(StandardSocketOptions.SO_SNDBUF)}.
 824      *
 825      * @return the value of the SO_SNDBUF option for this {@code DatagramSocket}
 826      * @throws    SocketException if there is an error in
 827      * the underlying protocol, such as an UDP error.
 828      * @see #setSendBufferSize
 829      * @see StandardSocketOptions#SO_SNDBUF
 830      * @since 1.2
 831      */
 832     public int getSendBufferSize() throws SocketException {
 833         return delegate().getSendBufferSize();
 834     }
 835 
 836     /**
 837      * Sets the SO_RCVBUF option to the specified value for this
 838      * {@code DatagramSocket}. The SO_RCVBUF option is used by
 839      * the network implementation as a hint to size the underlying
 840      * network I/O buffers. The SO_RCVBUF setting may also be used
 841      * by the network implementation to determine the maximum size
 842      * of the packet that can be received on this socket.
 843      * <p>
 844      * Because SO_RCVBUF is a hint, applications that want to
 845      * verify what size the buffers were set to should call
 846      * {@link #getReceiveBufferSize()}.
 847      * <p>
 848      * Increasing SO_RCVBUF may allow the network implementation
 849      * to buffer multiple packets when packets arrive faster than
 850      * are being received using {@link #receive(DatagramPacket)}.
 851      * <p>
 852      * Note: It is implementation specific if a packet larger
 853      * than SO_RCVBUF can be received.
 854      *
 855      * @apiNote
 856      * If {@code size > 0}, this method is equivalent to calling
 857      * {@link #setOption(SocketOption, Object)
 858      * setOption(StandardSocketOptions.SO_RCVBUF, size)}.
 859      *
 860      * @param size the size to which to set the receive buffer
 861      * size, in bytes. This value must be greater than 0.
 862      *
 863      * @throws    SocketException if there is an error in
 864      * the underlying protocol, such as an UDP error.
 865      * @throws    IllegalArgumentException if the value is 0 or is
 866      * negative.
 867      * @see #getReceiveBufferSize()
 868      * @see StandardSocketOptions#SO_RCVBUF
 869      * @since 1.2
 870      */
 871     public void setReceiveBufferSize(int size) throws SocketException {
 872         delegate().setReceiveBufferSize(size);
 873     }
 874 
 875     /**
 876      * Get value of the SO_RCVBUF option for this {@code DatagramSocket}, that is the
 877      * buffer size, in bytes, used by the platform for input on this {@code DatagramSocket}.
 878      *
 879      * @apiNote
 880      * This method is equivalent to calling {@link #getOption(SocketOption)
 881      * getOption(StandardSocketOptions.SO_RCVBUF)}.
 882      *
 883      * @return the value of the SO_RCVBUF option for this {@code DatagramSocket}
 884      * @throws    SocketException if there is an error in the underlying protocol, such as an UDP error.
 885      * @see #setReceiveBufferSize(int)
 886      * @see StandardSocketOptions#SO_RCVBUF
 887      * @since 1.2
 888      */
 889     public int getReceiveBufferSize() throws SocketException {
 890         return delegate().getReceiveBufferSize();
 891     }
 892 
 893     /**
 894      * Enable/disable the SO_REUSEADDR socket option.
 895      * <p>
 896      * For UDP sockets it may be necessary to bind more than one
 897      * socket to the same socket address. This is typically for the
 898      * purpose of receiving multicast packets
 899      * (See {@link java.net.MulticastSocket}). The
 900      * {@code SO_REUSEADDR} socket option allows multiple
 901      * sockets to be bound to the same socket address if the
 902      * {@code SO_REUSEADDR} socket option is enabled prior
 903      * to binding the socket using {@link #bind(SocketAddress)}.
 904      * <p>
 905      * Note: This functionality is not supported by all existing platforms,
 906      * so it is implementation specific whether this option will be ignored
 907      * or not. However, if it is not supported then
 908      * {@link #getReuseAddress()} will always return {@code false}.
 909      * <p>
 910      * When a {@code DatagramSocket} is created the initial setting
 911      * of {@code SO_REUSEADDR} is disabled.
 912      * <p>
 913      * The behaviour when {@code SO_REUSEADDR} is enabled or
 914      * disabled after a socket is bound (See {@link #isBound()})
 915      * is not defined.
 916      *
 917      * @apiNote
 918      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
 919      * setOption(StandardSocketOptions.SO_REUSEADDR, on)}.
 920      *
 921      * @param on  whether to enable or disable the
 922      * @throws    SocketException if an error occurs enabling or
 923      *            disabling the {@code SO_REUSEADDR} socket option,
 924      *            or the socket is closed.
 925      * @since 1.4
 926      * @see #getReuseAddress()
 927      * @see #bind(SocketAddress)
 928      * @see #isBound()
 929      * @see #isClosed()
 930      * @see StandardSocketOptions#SO_REUSEADDR
 931      */
 932     public void setReuseAddress(boolean on) throws SocketException {
 933         delegate().setReuseAddress(on);
 934     }
 935 
 936     /**
 937      * Tests if SO_REUSEADDR is enabled.
 938      *
 939      * @apiNote
 940      * This method is equivalent to calling {@link #getOption(SocketOption)
 941      * getOption(StandardSocketOptions.SO_REUSEADDR)}.
 942      *
 943      * @return a {@code boolean} indicating whether or not SO_REUSEADDR is enabled.
 944      * @throws    SocketException if there is an error
 945      * in the underlying protocol, such as an UDP error.
 946      * @since   1.4
 947      * @see #setReuseAddress(boolean)
 948      * @see StandardSocketOptions#SO_REUSEADDR
 949      */
 950     public boolean getReuseAddress() throws SocketException {
 951         return delegate().getReuseAddress();
 952     }
 953 
 954     /**
 955      * Enable/disable SO_BROADCAST.
 956      *
 957      * <p> Some operating systems may require that the Java virtual machine be
 958      * started with implementation specific privileges to enable this option or
 959      * send broadcast datagrams.
 960      *
 961      * @apiNote
 962      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
 963      * setOption(StandardSocketOptions.SO_BROADCAST, on)}.
 964      *
 965      * @param  on
 966      *         whether or not to have broadcast turned on.
 967      *
 968      * @throws  SocketException
 969      *          if there is an error in the underlying protocol, such as an UDP
 970      *          error.
 971      *
 972      * @since 1.4
 973      * @see #getBroadcast()
 974      * @see StandardSocketOptions#SO_BROADCAST
 975      */
 976     public void setBroadcast(boolean on) throws SocketException {
 977         delegate().setBroadcast(on);
 978     }
 979 
 980     /**
 981      * Tests if SO_BROADCAST is enabled.
 982      *
 983      * @apiNote
 984      * This method is equivalent to calling {@link #getOption(SocketOption)
 985      * getOption(StandardSocketOptions.SO_BROADCAST)}.
 986      *
 987      * @return a {@code boolean} indicating whether or not SO_BROADCAST is enabled.
 988      * @throws    SocketException if there is an error
 989      * in the underlying protocol, such as an UDP error.
 990      * @since 1.4
 991      * @see #setBroadcast(boolean)
 992      * @see StandardSocketOptions#SO_BROADCAST
 993      */
 994     public boolean getBroadcast() throws SocketException {
 995         return delegate().getBroadcast();
 996     }
 997 
 998     /**
 999      * Sets traffic class or type-of-service octet in the IP
1000      * datagram header for datagrams sent from this DatagramSocket.
1001      * As the underlying network implementation may ignore this
1002      * value applications should consider it a hint.
1003      *
1004      * <P> The tc <B>must</B> be in the range {@code 0 <= tc <=
1005      * 255} or an IllegalArgumentException will be thrown.
1006      * <p>Notes:
1007      * <p>For Internet Protocol v4 the value consists of an
1008      * {@code integer}, the least significant 8 bits of which
1009      * represent the value of the TOS octet in IP packets sent by
1010      * the socket.
1011      * RFC 1349 defines the TOS values as follows:
1012      *
1013      * <UL>
1014      * <LI><CODE>IPTOS_LOWCOST (0x02)</CODE></LI>
1015      * <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE></LI>
1016      * <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE></LI>
1017      * <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE></LI>
1018      * </UL>
1019      * The last low order bit is always ignored as this
1020      * corresponds to the MBZ (must be zero) bit.
1021      * <p>
1022      * Setting bits in the precedence field may result in a
1023      * SocketException indicating that the operation is not
1024      * permitted.
1025      * <p>
1026      * for Internet Protocol v6 {@code tc} is the value that
1027      * would be placed into the sin6_flowinfo field of the IP header.
1028      *
1029      * @apiNote
1030      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
1031      * setOption(StandardSocketOptions.IP_TOS, tc)}.
1032      *
1033      * @param tc        an {@code int} value for the bitset.
1034      * @throws SocketException if there is an error setting the
1035      * traffic class or type-of-service
1036      * @since 1.4
1037      * @see #getTrafficClass
1038      * @see StandardSocketOptions#IP_TOS
1039      */
1040     public void setTrafficClass(int tc) throws SocketException {
1041         delegate().setTrafficClass(tc);
1042     }
1043 
1044     /**
1045      * Gets traffic class or type-of-service in the IP datagram
1046      * header for packets sent from this DatagramSocket.
1047      * <p>
1048      * As the underlying network implementation may ignore the
1049      * traffic class or type-of-service set using {@link #setTrafficClass(int)}
1050      * this method may return a different value than was previously
1051      * set using the {@link #setTrafficClass(int)} method on this
1052      * DatagramSocket.
1053      *
1054      * @apiNote
1055      * This method is equivalent to calling {@link #getOption(SocketOption)
1056      * getOption(StandardSocketOptions.IP_TOS)}.
1057      *
1058      * @return the traffic class or type-of-service already set
1059      * @throws SocketException if there is an error obtaining the
1060      * traffic class or type-of-service value.
1061      * @since 1.4
1062      * @see #setTrafficClass(int)
1063      * @see StandardSocketOptions#IP_TOS
1064      */
1065     public int getTrafficClass() throws SocketException {
1066         return delegate().getTrafficClass();
1067     }
1068 
1069     /**
1070      * Closes this datagram socket.
1071      * <p>
1072      * Any thread currently blocked in {@link #receive} upon this socket
1073      * will throw a {@link SocketException}.
1074      *
1075      * <p> If this socket has an associated channel then the channel is closed
1076      * as well.
1077      *
1078      * @revised 1.4
1079      */
1080     public void close() {
1081         delegate().close();
1082     }
1083 
1084     /**
1085      * Returns whether the socket is closed or not.
1086      *
1087      * @return true if the socket has been closed
1088      * @since 1.4
1089      */
1090     public boolean isClosed() {
1091         return delegate().isClosed();
1092     }
1093 
1094     /**
1095      * Returns the unique {@link java.nio.channels.DatagramChannel} object
1096      * associated with this datagram socket, if any.
1097      *
1098      * <p> A datagram socket will have a channel if, and only if, the channel
1099      * itself was created via the {@link java.nio.channels.DatagramChannel#open
1100      * DatagramChannel.open} method.
1101      *
1102      * @return  the datagram channel associated with this datagram socket,
1103      *          or {@code null} if this socket was not created for a channel
1104      *
1105      * @since 1.4
1106      */
1107     public DatagramChannel getChannel() {
1108         return null;
1109     }
1110 
1111     /**
1112      * User defined factory for all datagram sockets.
1113      */
1114     private static volatile DatagramSocketImplFactory factory;
1115 
1116     /**
1117      * Sets the datagram socket implementation factory for the
1118      * application. The factory can be specified only once.
1119      * <p>
1120      * When an application creates a new datagram socket, the socket
1121      * implementation factory's {@code createDatagramSocketImpl} method is
1122      * called to create the actual datagram socket implementation.
1123      * <p>
1124      * Passing {@code null} to the method is a no-op unless the factory
1125      * was already set.
1126      *
1127      * <p>If there is a security manager, this method first calls
1128      * the security manager's {@code checkSetFactory} method
1129      * to ensure the operation is allowed.
1130      * This could result in a SecurityException.
1131      *
1132      * @param      fac   the desired factory.
1133      * @throws     IOException  if an I/O error occurs when setting the
1134      *              datagram socket factory.
1135      * @throws     SocketException  if the factory is already defined.
1136      * @throws     SecurityException  if a security manager exists and its
1137      *             {@code checkSetFactory} method doesn't allow the operation.
1138      * @see       java.net.DatagramSocketImplFactory#createDatagramSocketImpl()
1139      * @see       SecurityManager#checkSetFactory
1140      * @since 1.3
1141      *
1142      * @deprecated Use {@link DatagramChannel}, or subclass {@code DatagramSocket}
1143      *    directly.
1144      *    <br> This method provided a way in early JDK releases to replace the
1145      *    system wide implementation of {@code DatagramSocket}. It has been mostly
1146      *    obsolete since Java 1.4. If required, a {@code DatagramSocket} can be
1147      *    created to use a custom implementation by extending {@code DatagramSocket}
1148      *    and using the {@linkplain #DatagramSocket(DatagramSocketImpl) protected
1149      *    constructor} that takes an {@linkplain DatagramSocketImpl implementation}
1150      *    as a parameter.
1151      */
1152     @Deprecated(since = "17")
1153     public static synchronized void
1154     setDatagramSocketImplFactory(DatagramSocketImplFactory fac)
1155             throws IOException
1156     {
1157         if (factory != null) {
1158             throw new SocketException("factory already defined");
1159         }
1160         @SuppressWarnings("removal")
1161         SecurityManager security = System.getSecurityManager();
1162         if (security != null) {
1163             security.checkSetFactory();
1164         }
1165         factory = fac;
1166     }
1167 
1168     /**
1169      * Sets the value of a socket option.
1170      *
1171      * @param <T> The type of the socket option value
1172      * @param name The socket option
1173      * @param value The value of the socket option. A value of {@code null}
1174      *              may be valid for some options.
1175      *
1176      * @return this DatagramSocket
1177      *
1178      * @throws UnsupportedOperationException if the datagram socket
1179      *         does not support the option.
1180      *
1181      * @throws IllegalArgumentException if the value is not valid for
1182      *         the option.
1183      *
1184      * @throws IOException if an I/O error occurs, or if the socket is closed.
1185      *
1186      * @throws SecurityException if a security manager is set and if the socket
1187      *         option requires a security permission and if the caller does
1188      *         not have the required permission.
1189      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1190      *         do not require any security permission.
1191      *
1192      * @throws NullPointerException if name is {@code null}
1193      *
1194      * @since 9
1195      */
1196     public <T> DatagramSocket setOption(SocketOption<T> name, T value)
1197         throws IOException
1198     {
1199         delegate().setOption(name, value);
1200         return this;
1201     }
1202 
1203     /**
1204      * Returns the value of a socket option.
1205      *
1206      * @param <T> The type of the socket option value
1207      * @param name The socket option
1208      *
1209      * @return The value of the socket option.
1210      *
1211      * @throws UnsupportedOperationException if the datagram socket
1212      *         does not support the option.
1213      *
1214      * @throws IOException if an I/O error occurs, or if the socket is closed.
1215      *
1216      * @throws NullPointerException if name is {@code null}
1217      *
1218      * @throws SecurityException if a security manager is set and if the socket
1219      *         option requires a security permission and if the caller does
1220      *         not have the required permission.
1221      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1222      *         do not require any security permission.
1223      *
1224      * @since 9
1225      */
1226     public <T> T getOption(SocketOption<T> name) throws IOException {
1227         return delegate().getOption(name);
1228     }
1229 
1230     /**
1231      * Returns a set of the socket options supported by this socket.
1232      *
1233      * This method will continue to return the set of options even after
1234      * the socket has been closed.
1235      *
1236      * @return A set of the socket options supported by this socket. This set
1237      *        may be empty if the socket's DatagramSocketImpl cannot be created.
1238      *
1239      * @since 9
1240      */
1241     public Set<SocketOption<?>> supportedOptions() {
1242         return delegate().supportedOptions();
1243     }
1244 
1245     /**
1246      * Joins a multicast group.
1247      *
1248      * <p> In order to join a multicast group, the caller should specify
1249      * the IP address of the multicast group to join, and the local
1250      * {@linkplain NetworkInterface network interface} to receive multicast
1251      * packets from.
1252      * <ul>
1253      *  <li> The {@code mcastaddr} argument indicates the IP address
1254      *   of the multicast group to join. For historical reasons this is
1255      *   specified as a {@code SocketAddress}.
1256      *   The default implementation only supports {@link InetSocketAddress} and
1257      *   the {@link InetSocketAddress#getPort() port} information is ignored.
1258      *  </li>
1259      *  <li> The {@code netIf} argument specifies the local interface to receive
1260      *       multicast datagram packets, or {@code null} to defer to the interface
1261      *       set for outgoing multicast datagrams.
1262      *       If {@code null}, and no interface has been set, the behaviour is
1263      *       unspecified: any interface may be selected or the operation may fail
1264      *       with a {@code SocketException}.
1265      *  </li>
1266      * </ul>
1267      *
1268      * <p> It is possible to call this method several times to join
1269      * several different multicast groups, or join the same group
1270      * in several different networks. However, if the socket is already a
1271      * member of the group, an {@link IOException} will be thrown.
1272      *
1273      * <p>If there is a security manager, this method first
1274      * calls its {@code checkMulticast} method with the {@code mcastaddr}
1275      * argument as its argument.
1276      *
1277      * @apiNote The default interface for sending outgoing multicast datagrams
1278      * can be configured with {@link #setOption(SocketOption, Object)}
1279      * with {@link StandardSocketOptions#IP_MULTICAST_IF}.
1280      *
1281      * @param  mcastaddr indicates the multicast address to join.
1282      * @param  netIf specifies the local interface to receive multicast
1283      *         datagram packets, or {@code null}.
1284      * @throws IOException if there is an error joining, or when the address
1285      *         is not a multicast address, or the platform does not support
1286      *         multicasting
1287      * @throws SecurityException if a security manager exists and its
1288      *         {@code checkMulticast} method doesn't allow the join.
1289      * @throws IllegalArgumentException if mcastaddr is {@code null} or is a
1290      *         SocketAddress subclass not supported by this socket
1291      * @see    SecurityManager#checkMulticast(InetAddress)
1292      * @see    DatagramChannel#join(InetAddress, NetworkInterface)
1293      * @see    StandardSocketOptions#IP_MULTICAST_IF
1294      * @since  17
1295      */
1296     public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
1297             throws IOException {
1298         delegate().joinGroup(mcastaddr, netIf);
1299     }
1300 
1301     /**
1302      * Leave a multicast group on a specified local interface.
1303      *
1304      * <p>If there is a security manager, this method first
1305      * calls its {@code checkMulticast} method with the
1306      * {@code mcastaddr} argument as its argument.
1307      *
1308      * @apiNote
1309      * The {@code mcastaddr} and {@code netIf} arguments should identify
1310      * a multicast group that was previously {@linkplain
1311      * #joinGroup(SocketAddress, NetworkInterface) joined} by
1312      * this {@code DatagramSocket}.
1313      * <p> It is possible to call this method several times to leave
1314      * multiple different multicast groups previously joined, or leave
1315      * the same group previously joined in multiple different networks.
1316      * However, if the socket is not a member of the specified group
1317      * in the specified network, an {@link IOException} will be
1318      * thrown.
1319      *
1320      * @param  mcastaddr is the multicast address to leave. This should
1321      *         contain the same IP address than that used for {@linkplain
1322      *         #joinGroup(SocketAddress, NetworkInterface) joining}
1323      *         the group.
1324      * @param  netIf specifies the local interface or {@code null} to defer
1325      *         to the interface set for outgoing multicast datagrams.
1326      *         If {@code null}, and no interface has been set, the behaviour
1327      *         is unspecified: any interface may be selected or the operation
1328      *         may fail with a {@code SocketException}.
1329      * @throws IOException if there is an error leaving or when the address
1330      *         is not a multicast address.
1331      * @throws SecurityException if a security manager exists and its
1332      *         {@code checkMulticast} method doesn't allow the operation.
1333      * @throws IllegalArgumentException if mcastaddr is {@code null} or is a
1334      *         SocketAddress subclass not supported by this socket.
1335      * @see    SecurityManager#checkMulticast(InetAddress)
1336      * @see    #joinGroup(SocketAddress, NetworkInterface)
1337      * @see    StandardSocketOptions#IP_MULTICAST_IF
1338      * @since  17
1339      */
1340     public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
1341             throws IOException {
1342         delegate().leaveGroup(mcastaddr, netIf);
1343     }
1344 
1345     // Temporary solution until JDK-8237352 is addressed
1346     private static final SocketAddress NO_DELEGATE = new SocketAddress() {};
1347 
1348     /**
1349      * Best effort to convert an {@link IOException}
1350      * into a {@link SocketException}.
1351      *
1352      * @param e an instance of {@link IOException}
1353      * @return an instance of {@link SocketException}
1354      */
1355     private static SocketException toSocketException(IOException e) {
1356         if (e instanceof SocketException)
1357             return (SocketException) e;
1358         Throwable cause = e.getCause();
1359         if (cause instanceof SocketException)
1360             return (SocketException) cause;
1361         SocketException se = new SocketException(e.getMessage());
1362         se.initCause(e);
1363         return se;
1364     }
1365 
1366     /**
1367      * Creates a delegate for the specific requested {@code type}. This method should
1368      * only be called by {@code DatagramSocket} and {@code MulticastSocket}
1369      * public constructors.
1370      *
1371      * @param bindaddr An address to bind to, or {@code null} if creating an unbound
1372      *                 socket.
1373      * @param type     This is either {@code MulticastSocket.class}, if the delegate needs
1374      *                 to support joining multicast groups, or {@code DatagramSocket.class},
1375      *                 if it doesn't. Typically, this will be {@code DatagramSocket.class}
1376      *                 when creating a delegate for {@code DatagramSocket}, and
1377      *                 {@code MulticastSocket.class} when creating a delegate for
1378      *                 {@code MulticastSocket}.
1379      * @param <T>      The target type for which the delegate is created.
1380      *                 This is either {@code java.net.DatagramSocket} or
1381      *                 {@code java.net.MulticastSocket}.
1382      * @return {@code null} if {@code bindaddr == NO_DELEGATE}, otherwise returns a
1383      * delegate for the requested {@code type}.
1384      * @throws SocketException if an exception occurs while creating or binding
1385      *                         the delegate.
1386      */
1387     static <T extends DatagramSocket> T createDelegate(SocketAddress bindaddr, Class<T> type)
1388             throws SocketException {
1389 
1390         // Temporary solution until JDK-8237352 is addressed
1391         if (bindaddr == NO_DELEGATE) return null;
1392 
1393         assert type == DatagramSocket.class || type == MulticastSocket.class;
1394         boolean multicast = (type == MulticastSocket.class);
1395         DatagramSocket delegate = null;
1396         boolean initialized = false;
1397         try {
1398             DatagramSocketImplFactory factory = DatagramSocket.factory;
1399             if (factory != null) {
1400                 // create legacy DatagramSocket delegate
1401                 DatagramSocketImpl impl = factory.createDatagramSocketImpl();
1402                 Objects.requireNonNull(impl,
1403                         "Implementation returned by installed DatagramSocketImplFactory is null");
1404                 delegate = new NetMulticastSocket(impl);
1405                 ((NetMulticastSocket) delegate).getImpl(); // ensure impl.create() is called.
1406             } else {
1407                 // create NIO adaptor
1408                 delegate = DefaultSelectorProvider.get()
1409                         .openUninterruptibleDatagramChannel()
1410                         .socket();
1411             }
1412 
1413             if (multicast) {
1414                 // set reuseaddress if multicasting
1415                 // (must be set before binding)
1416                 delegate.setReuseAddress(true);
1417             }
1418 
1419             if (bindaddr != null) {
1420                 // bind if needed
1421                 delegate.bind(bindaddr);
1422             }
1423 
1424             // enable broadcast if possible
1425             try {
1426                 delegate.setBroadcast(true);
1427             } catch (IOException ioe) {
1428             }
1429 
1430             initialized = true;
1431         } catch (IOException ioe) {
1432             throw toSocketException(ioe);
1433         } finally {
1434             // make sure the delegate is closed if anything
1435             // went wrong
1436             if (!initialized && delegate != null) {
1437                 delegate.close();
1438             }
1439         }
1440         @SuppressWarnings("unchecked")
1441         T result = (T) delegate;
1442         return result;
1443     }
1444 
1445 }