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. The
 675      * {@code length} field of the datagram packet object contains





 676      * the length of the received message. If the message is longer than
 677      * the packet's length, the message is truncated.
 678      * <p>
 679      * If there is a security manager, and the socket is not currently
 680      * connected to a remote address, a packet cannot be received if the
 681      * security manager's {@code checkAccept} method does not allow it.
 682      * Datagrams that are not permitted by the security manager are silently
 683      * discarded.
 684      *
 685      * @param      p   the {@code DatagramPacket} into which to place
 686      *                 the incoming data.
 687      * @throws     IOException  if an I/O error occurs.
 688      * @throws     SocketTimeoutException  if setSoTimeout was previously called
 689      *                 and the timeout has expired.
 690      * @throws     PortUnreachableException may be thrown if the socket is connected
 691      *             to a currently unreachable destination. Note, there is no guarantee that the
 692      *             exception will be thrown.
 693      * @throws     java.nio.channels.IllegalBlockingModeException
 694      *             if this socket has an associated channel,
 695      *             and the channel is in non-blocking mode.
 696      * @see        java.net.DatagramPacket
 697      * @see        java.net.DatagramSocket
 698      * @revised 1.4
 699      */
 700     public void receive(DatagramPacket p) throws IOException {
 701         delegate().receive(p);
 702     }
 703 
 704     /**
 705      * Gets the local address to which the socket is bound.
 706      *
 707      * <p>If there is a security manager, its
 708      * {@code checkConnect} method is first called
 709      * with the host address and {@code -1}
 710      * as its arguments to see if the operation is allowed.
 711      *
 712      * @see SecurityManager#checkConnect
 713      * @return  the local address to which the socket is bound,
 714      *          {@code null} if the socket is closed, or
 715      *          an {@code InetAddress} representing
 716      *          {@link InetAddress#isAnyLocalAddress wildcard}
 717      *          address if either the socket is not bound, or
 718      *          the security manager {@code checkConnect}
 719      *          method does not allow the operation
 720      * @since   1.1
 721      */
 722     public InetAddress getLocalAddress() {
 723         return delegate().getLocalAddress();
 724     }
 725 
 726     /**
 727      * Returns the port number on the local host to which this socket
 728      * is bound.
 729      *
 730      * @return  the port number on the local host to which this socket is bound,
 731      *          {@code -1} if the socket is closed, or
 732      *          {@code 0} if it is not bound yet.
 733      */
 734     public int getLocalPort() {
 735         return delegate().getLocalPort();
 736     }
 737 
 738     /**
 739      * Enable/disable SO_TIMEOUT with the specified timeout, in
 740      * milliseconds. With this option set to a positive timeout value,
 741      * a call to receive() for this DatagramSocket
 742      * will block for only this amount of time.  If the timeout expires,
 743      * a <B>java.net.SocketTimeoutException</B> is raised, though the
 744      * DatagramSocket is still valid. A timeout of zero is interpreted
 745      * as an infinite timeout.
 746      * The option <B>must</B> be enabled prior to entering the blocking
 747      * operation to have effect.
 748      *
 749      * @param timeout the specified timeout in milliseconds.
 750      * @throws SocketException if there is an error in the underlying protocol, such as an UDP error.
 751      * @throws IllegalArgumentException if {@code timeout} is negative
 752      * @since   1.1
 753      * @see #getSoTimeout()
 754      */
 755     public void setSoTimeout(int timeout) throws SocketException {
 756         delegate().setSoTimeout(timeout);
 757     }
 758 
 759     /**
 760      * Retrieve setting for SO_TIMEOUT.  0 returns implies that the
 761      * option is disabled (i.e., timeout of infinity).
 762      *
 763      * @return the setting for SO_TIMEOUT
 764      * @throws SocketException if there is an error in the underlying protocol, such as an UDP error.
 765      * @since   1.1
 766      * @see #setSoTimeout(int)
 767      */
 768     public int getSoTimeout() throws SocketException {
 769         return delegate().getSoTimeout();
 770     }
 771 
 772     /**
 773      * Sets the SO_SNDBUF option to the specified value for this
 774      * {@code DatagramSocket}. The SO_SNDBUF option is used by the
 775      * network implementation as a hint to size the underlying
 776      * network I/O buffers. The SO_SNDBUF setting may also be used
 777      * by the network implementation to determine the maximum size
 778      * of the packet that can be sent on this socket.
 779      * <p>
 780      * As SO_SNDBUF is a hint, applications that want to verify
 781      * what size the buffer is should call {@link #getSendBufferSize()}.
 782      * <p>
 783      * Increasing the buffer size may allow multiple outgoing packets
 784      * to be queued by the network implementation when the send rate
 785      * is high.
 786      * <p>
 787      * Note: If {@link #send(DatagramPacket)} is used to send a
 788      * {@code DatagramPacket} that is larger than the setting
 789      * of SO_SNDBUF then it is implementation specific if the
 790      * packet is sent or discarded.
 791      *
 792      * @apiNote
 793      * If {@code size > 0}, this method is equivalent to calling
 794      * {@link #setOption(SocketOption, Object)
 795      * setOption(StandardSocketOptions.SO_SNDBUF, size)}.
 796      *
 797      * @param size the size to which to set the send buffer
 798      * size, in bytes. This value must be greater than 0.
 799      *
 800      * @throws    SocketException if there is an error
 801      * in the underlying protocol, such as an UDP error.
 802      * @throws    IllegalArgumentException if the value is 0 or is
 803      * negative.
 804      * @see #getSendBufferSize()
 805      * @see StandardSocketOptions#SO_SNDBUF
 806      * @since 1.2
 807      */
 808     public void setSendBufferSize(int size) throws SocketException {
 809         delegate().setSendBufferSize(size);
 810     }
 811 
 812     /**
 813      * Get value of the SO_SNDBUF option for this {@code DatagramSocket}, that is the
 814      * buffer size, in bytes, used by the platform for output on this {@code DatagramSocket}.
 815      *
 816      * @apiNote
 817      * This method is equivalent to calling {@link #getOption(SocketOption)
 818      * getOption(StandardSocketOptions.SO_SNDBUF)}.
 819      *
 820      * @return the value of the SO_SNDBUF option for this {@code DatagramSocket}
 821      * @throws    SocketException if there is an error in
 822      * the underlying protocol, such as an UDP error.
 823      * @see #setSendBufferSize
 824      * @see StandardSocketOptions#SO_SNDBUF
 825      * @since 1.2
 826      */
 827     public int getSendBufferSize() throws SocketException {
 828         return delegate().getSendBufferSize();
 829     }
 830 
 831     /**
 832      * Sets the SO_RCVBUF option to the specified value for this
 833      * {@code DatagramSocket}. The SO_RCVBUF option is used by
 834      * the network implementation as a hint to size the underlying
 835      * network I/O buffers. The SO_RCVBUF setting may also be used
 836      * by the network implementation to determine the maximum size
 837      * of the packet that can be received on this socket.
 838      * <p>
 839      * Because SO_RCVBUF is a hint, applications that want to
 840      * verify what size the buffers were set to should call
 841      * {@link #getReceiveBufferSize()}.
 842      * <p>
 843      * Increasing SO_RCVBUF may allow the network implementation
 844      * to buffer multiple packets when packets arrive faster than
 845      * are being received using {@link #receive(DatagramPacket)}.
 846      * <p>
 847      * Note: It is implementation specific if a packet larger
 848      * than SO_RCVBUF can be received.
 849      *
 850      * @apiNote
 851      * If {@code size > 0}, this method is equivalent to calling
 852      * {@link #setOption(SocketOption, Object)
 853      * setOption(StandardSocketOptions.SO_RCVBUF, size)}.
 854      *
 855      * @param size the size to which to set the receive buffer
 856      * size, in bytes. This value must be greater than 0.
 857      *
 858      * @throws    SocketException if there is an error in
 859      * the underlying protocol, such as an UDP error.
 860      * @throws    IllegalArgumentException if the value is 0 or is
 861      * negative.
 862      * @see #getReceiveBufferSize()
 863      * @see StandardSocketOptions#SO_RCVBUF
 864      * @since 1.2
 865      */
 866     public void setReceiveBufferSize(int size) throws SocketException {
 867         delegate().setReceiveBufferSize(size);
 868     }
 869 
 870     /**
 871      * Get value of the SO_RCVBUF option for this {@code DatagramSocket}, that is the
 872      * buffer size, in bytes, used by the platform for input on this {@code DatagramSocket}.
 873      *
 874      * @apiNote
 875      * This method is equivalent to calling {@link #getOption(SocketOption)
 876      * getOption(StandardSocketOptions.SO_RCVBUF)}.
 877      *
 878      * @return the value of the SO_RCVBUF option for this {@code DatagramSocket}
 879      * @throws    SocketException if there is an error in the underlying protocol, such as an UDP error.
 880      * @see #setReceiveBufferSize(int)
 881      * @see StandardSocketOptions#SO_RCVBUF
 882      * @since 1.2
 883      */
 884     public int getReceiveBufferSize() throws SocketException {
 885         return delegate().getReceiveBufferSize();
 886     }
 887 
 888     /**
 889      * Enable/disable the SO_REUSEADDR socket option.
 890      * <p>
 891      * For UDP sockets it may be necessary to bind more than one
 892      * socket to the same socket address. This is typically for the
 893      * purpose of receiving multicast packets
 894      * (See {@link java.net.MulticastSocket}). The
 895      * {@code SO_REUSEADDR} socket option allows multiple
 896      * sockets to be bound to the same socket address if the
 897      * {@code SO_REUSEADDR} socket option is enabled prior
 898      * to binding the socket using {@link #bind(SocketAddress)}.
 899      * <p>
 900      * Note: This functionality is not supported by all existing platforms,
 901      * so it is implementation specific whether this option will be ignored
 902      * or not. However, if it is not supported then
 903      * {@link #getReuseAddress()} will always return {@code false}.
 904      * <p>
 905      * When a {@code DatagramSocket} is created the initial setting
 906      * of {@code SO_REUSEADDR} is disabled.
 907      * <p>
 908      * The behaviour when {@code SO_REUSEADDR} is enabled or
 909      * disabled after a socket is bound (See {@link #isBound()})
 910      * is not defined.
 911      *
 912      * @apiNote
 913      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
 914      * setOption(StandardSocketOptions.SO_REUSEADDR, on)}.
 915      *
 916      * @param on  whether to enable or disable the
 917      * @throws    SocketException if an error occurs enabling or
 918      *            disabling the {@code SO_REUSEADDR} socket option,
 919      *            or the socket is closed.
 920      * @since 1.4
 921      * @see #getReuseAddress()
 922      * @see #bind(SocketAddress)
 923      * @see #isBound()
 924      * @see #isClosed()
 925      * @see StandardSocketOptions#SO_REUSEADDR
 926      */
 927     public void setReuseAddress(boolean on) throws SocketException {
 928         delegate().setReuseAddress(on);
 929     }
 930 
 931     /**
 932      * Tests if SO_REUSEADDR is enabled.
 933      *
 934      * @apiNote
 935      * This method is equivalent to calling {@link #getOption(SocketOption)
 936      * getOption(StandardSocketOptions.SO_REUSEADDR)}.
 937      *
 938      * @return a {@code boolean} indicating whether or not SO_REUSEADDR is enabled.
 939      * @throws    SocketException if there is an error
 940      * in the underlying protocol, such as an UDP error.
 941      * @since   1.4
 942      * @see #setReuseAddress(boolean)
 943      * @see StandardSocketOptions#SO_REUSEADDR
 944      */
 945     public boolean getReuseAddress() throws SocketException {
 946         return delegate().getReuseAddress();
 947     }
 948 
 949     /**
 950      * Enable/disable SO_BROADCAST.
 951      *
 952      * <p> Some operating systems may require that the Java virtual machine be
 953      * started with implementation specific privileges to enable this option or
 954      * send broadcast datagrams.
 955      *
 956      * @apiNote
 957      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
 958      * setOption(StandardSocketOptions.SO_BROADCAST, on)}.
 959      *
 960      * @param  on
 961      *         whether or not to have broadcast turned on.
 962      *
 963      * @throws  SocketException
 964      *          if there is an error in the underlying protocol, such as an UDP
 965      *          error.
 966      *
 967      * @since 1.4
 968      * @see #getBroadcast()
 969      * @see StandardSocketOptions#SO_BROADCAST
 970      */
 971     public void setBroadcast(boolean on) throws SocketException {
 972         delegate().setBroadcast(on);
 973     }
 974 
 975     /**
 976      * Tests if SO_BROADCAST is enabled.
 977      *
 978      * @apiNote
 979      * This method is equivalent to calling {@link #getOption(SocketOption)
 980      * getOption(StandardSocketOptions.SO_BROADCAST)}.
 981      *
 982      * @return a {@code boolean} indicating whether or not SO_BROADCAST is enabled.
 983      * @throws    SocketException if there is an error
 984      * in the underlying protocol, such as an UDP error.
 985      * @since 1.4
 986      * @see #setBroadcast(boolean)
 987      * @see StandardSocketOptions#SO_BROADCAST
 988      */
 989     public boolean getBroadcast() throws SocketException {
 990         return delegate().getBroadcast();
 991     }
 992 
 993     /**
 994      * Sets traffic class or type-of-service octet in the IP
 995      * datagram header for datagrams sent from this DatagramSocket.
 996      * As the underlying network implementation may ignore this
 997      * value applications should consider it a hint.
 998      *
 999      * <P> The tc <B>must</B> be in the range {@code 0 <= tc <=
1000      * 255} or an IllegalArgumentException will be thrown.
1001      * <p>Notes:
1002      * <p>For Internet Protocol v4 the value consists of an
1003      * {@code integer}, the least significant 8 bits of which
1004      * represent the value of the TOS octet in IP packets sent by
1005      * the socket.
1006      * RFC 1349 defines the TOS values as follows:
1007      *
1008      * <UL>
1009      * <LI><CODE>IPTOS_LOWCOST (0x02)</CODE></LI>
1010      * <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE></LI>
1011      * <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE></LI>
1012      * <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE></LI>
1013      * </UL>
1014      * The last low order bit is always ignored as this
1015      * corresponds to the MBZ (must be zero) bit.
1016      * <p>
1017      * Setting bits in the precedence field may result in a
1018      * SocketException indicating that the operation is not
1019      * permitted.
1020      * <p>
1021      * for Internet Protocol v6 {@code tc} is the value that
1022      * would be placed into the sin6_flowinfo field of the IP header.
1023      *
1024      * @apiNote
1025      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
1026      * setOption(StandardSocketOptions.IP_TOS, tc)}.
1027      *
1028      * @param tc        an {@code int} value for the bitset.
1029      * @throws SocketException if there is an error setting the
1030      * traffic class or type-of-service
1031      * @since 1.4
1032      * @see #getTrafficClass
1033      * @see StandardSocketOptions#IP_TOS
1034      */
1035     public void setTrafficClass(int tc) throws SocketException {
1036         delegate().setTrafficClass(tc);
1037     }
1038 
1039     /**
1040      * Gets traffic class or type-of-service in the IP datagram
1041      * header for packets sent from this DatagramSocket.
1042      * <p>
1043      * As the underlying network implementation may ignore the
1044      * traffic class or type-of-service set using {@link #setTrafficClass(int)}
1045      * this method may return a different value than was previously
1046      * set using the {@link #setTrafficClass(int)} method on this
1047      * DatagramSocket.
1048      *
1049      * @apiNote
1050      * This method is equivalent to calling {@link #getOption(SocketOption)
1051      * getOption(StandardSocketOptions.IP_TOS)}.
1052      *
1053      * @return the traffic class or type-of-service already set
1054      * @throws SocketException if there is an error obtaining the
1055      * traffic class or type-of-service value.
1056      * @since 1.4
1057      * @see #setTrafficClass(int)
1058      * @see StandardSocketOptions#IP_TOS
1059      */
1060     public int getTrafficClass() throws SocketException {
1061         return delegate().getTrafficClass();
1062     }
1063 
1064     /**
1065      * Closes this datagram socket.
1066      * <p>
1067      * Any thread currently blocked in {@link #receive} upon this socket
1068      * will throw a {@link SocketException}.
1069      *
1070      * <p> If this socket has an associated channel then the channel is closed
1071      * as well.
1072      *
1073      * @revised 1.4
1074      */
1075     public void close() {
1076         delegate().close();
1077     }
1078 
1079     /**
1080      * Returns whether the socket is closed or not.
1081      *
1082      * @return true if the socket has been closed
1083      * @since 1.4
1084      */
1085     public boolean isClosed() {
1086         return delegate().isClosed();
1087     }
1088 
1089     /**
1090      * Returns the unique {@link java.nio.channels.DatagramChannel} object
1091      * associated with this datagram socket, if any.
1092      *
1093      * <p> A datagram socket will have a channel if, and only if, the channel
1094      * itself was created via the {@link java.nio.channels.DatagramChannel#open
1095      * DatagramChannel.open} method.
1096      *
1097      * @return  the datagram channel associated with this datagram socket,
1098      *          or {@code null} if this socket was not created for a channel
1099      *
1100      * @since 1.4
1101      */
1102     public DatagramChannel getChannel() {
1103         return null;
1104     }
1105 
1106     /**
1107      * User defined factory for all datagram sockets.
1108      */
1109     private static volatile DatagramSocketImplFactory factory;
1110 
1111     /**
1112      * Sets the datagram socket implementation factory for the
1113      * application. The factory can be specified only once.
1114      * <p>
1115      * When an application creates a new datagram socket, the socket
1116      * implementation factory's {@code createDatagramSocketImpl} method is
1117      * called to create the actual datagram socket implementation.
1118      * <p>
1119      * Passing {@code null} to the method is a no-op unless the factory
1120      * was already set.
1121      *
1122      * <p>If there is a security manager, this method first calls
1123      * the security manager's {@code checkSetFactory} method
1124      * to ensure the operation is allowed.
1125      * This could result in a SecurityException.
1126      *
1127      * @param      fac   the desired factory.
1128      * @throws     IOException  if an I/O error occurs when setting the
1129      *              datagram socket factory.
1130      * @throws     SocketException  if the factory is already defined.
1131      * @throws     SecurityException  if a security manager exists and its
1132      *             {@code checkSetFactory} method doesn't allow the operation.
1133      * @see       java.net.DatagramSocketImplFactory#createDatagramSocketImpl()
1134      * @see       SecurityManager#checkSetFactory
1135      * @since 1.3
1136      *
1137      * @deprecated Use {@link DatagramChannel}, or subclass {@code DatagramSocket}
1138      *    directly.
1139      *    <br> This method provided a way in early JDK releases to replace the
1140      *    system wide implementation of {@code DatagramSocket}. It has been mostly
1141      *    obsolete since Java 1.4. If required, a {@code DatagramSocket} can be
1142      *    created to use a custom implementation by extending {@code DatagramSocket}
1143      *    and using the {@linkplain #DatagramSocket(DatagramSocketImpl) protected
1144      *    constructor} that takes an {@linkplain DatagramSocketImpl implementation}
1145      *    as a parameter.
1146      */
1147     @Deprecated(since = "17")
1148     public static synchronized void
1149     setDatagramSocketImplFactory(DatagramSocketImplFactory fac)
1150             throws IOException
1151     {
1152         if (factory != null) {
1153             throw new SocketException("factory already defined");
1154         }
1155         @SuppressWarnings("removal")
1156         SecurityManager security = System.getSecurityManager();
1157         if (security != null) {
1158             security.checkSetFactory();
1159         }
1160         factory = fac;
1161     }
1162 
1163     /**
1164      * Sets the value of a socket option.
1165      *
1166      * @param <T> The type of the socket option value
1167      * @param name The socket option
1168      * @param value The value of the socket option. A value of {@code null}
1169      *              may be valid for some options.
1170      *
1171      * @return this DatagramSocket
1172      *
1173      * @throws UnsupportedOperationException if the datagram socket
1174      *         does not support the option.
1175      *
1176      * @throws IllegalArgumentException if the value is not valid for
1177      *         the option.
1178      *
1179      * @throws IOException if an I/O error occurs, or if the socket is closed.
1180      *
1181      * @throws SecurityException if a security manager is set and if the socket
1182      *         option requires a security permission and if the caller does
1183      *         not have the required permission.
1184      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1185      *         do not require any security permission.
1186      *
1187      * @throws NullPointerException if name is {@code null}
1188      *
1189      * @since 9
1190      */
1191     public <T> DatagramSocket setOption(SocketOption<T> name, T value)
1192         throws IOException
1193     {
1194         delegate().setOption(name, value);
1195         return this;
1196     }
1197 
1198     /**
1199      * Returns the value of a socket option.
1200      *
1201      * @param <T> The type of the socket option value
1202      * @param name The socket option
1203      *
1204      * @return The value of the socket option.
1205      *
1206      * @throws UnsupportedOperationException if the datagram socket
1207      *         does not support the option.
1208      *
1209      * @throws IOException if an I/O error occurs, or if the socket is closed.
1210      *
1211      * @throws NullPointerException if name is {@code null}
1212      *
1213      * @throws SecurityException if a security manager is set and if the socket
1214      *         option requires a security permission and if the caller does
1215      *         not have the required permission.
1216      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1217      *         do not require any security permission.
1218      *
1219      * @since 9
1220      */
1221     public <T> T getOption(SocketOption<T> name) throws IOException {
1222         return delegate().getOption(name);
1223     }
1224 
1225     /**
1226      * Returns a set of the socket options supported by this socket.
1227      *
1228      * This method will continue to return the set of options even after
1229      * the socket has been closed.
1230      *
1231      * @return A set of the socket options supported by this socket. This set
1232      *        may be empty if the socket's DatagramSocketImpl cannot be created.
1233      *
1234      * @since 9
1235      */
1236     public Set<SocketOption<?>> supportedOptions() {
1237         return delegate().supportedOptions();
1238     }
1239 
1240     /**
1241      * Joins a multicast group.
1242      *
1243      * <p> In order to join a multicast group, the caller should specify
1244      * the IP address of the multicast group to join, and the local
1245      * {@linkplain NetworkInterface network interface} to receive multicast
1246      * packets from.
1247      * <ul>
1248      *  <li> The {@code mcastaddr} argument indicates the IP address
1249      *   of the multicast group to join. For historical reasons this is
1250      *   specified as a {@code SocketAddress}.
1251      *   The default implementation only supports {@link InetSocketAddress} and
1252      *   the {@link InetSocketAddress#getPort() port} information is ignored.
1253      *  </li>
1254      *  <li> The {@code netIf} argument specifies the local interface to receive
1255      *       multicast datagram packets, or {@code null} to defer to the interface
1256      *       set for outgoing multicast datagrams.
1257      *       If {@code null}, and no interface has been set, the behaviour is
1258      *       unspecified: any interface may be selected or the operation may fail
1259      *       with a {@code SocketException}.
1260      *  </li>
1261      * </ul>
1262      *
1263      * <p> It is possible to call this method several times to join
1264      * several different multicast groups, or join the same group
1265      * in several different networks. However, if the socket is already a
1266      * member of the group, an {@link IOException} will be thrown.
1267      *
1268      * <p>If there is a security manager, this method first
1269      * calls its {@code checkMulticast} method with the {@code mcastaddr}
1270      * argument as its argument.
1271      *
1272      * @apiNote The default interface for sending outgoing multicast datagrams
1273      * can be configured with {@link #setOption(SocketOption, Object)}
1274      * with {@link StandardSocketOptions#IP_MULTICAST_IF}.
1275      *
1276      * @param  mcastaddr indicates the multicast address to join.
1277      * @param  netIf specifies the local interface to receive multicast
1278      *         datagram packets, or {@code null}.
1279      * @throws IOException if there is an error joining, or when the address
1280      *         is not a multicast address, or the platform does not support
1281      *         multicasting
1282      * @throws SecurityException if a security manager exists and its
1283      *         {@code checkMulticast} method doesn't allow the join.
1284      * @throws IllegalArgumentException if mcastaddr is {@code null} or is a
1285      *         SocketAddress subclass not supported by this socket
1286      * @see    SecurityManager#checkMulticast(InetAddress)
1287      * @see    DatagramChannel#join(InetAddress, NetworkInterface)
1288      * @see    StandardSocketOptions#IP_MULTICAST_IF
1289      * @since  17
1290      */
1291     public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
1292             throws IOException {
1293         delegate().joinGroup(mcastaddr, netIf);
1294     }
1295 
1296     /**
1297      * Leave a multicast group on a specified local interface.
1298      *
1299      * <p>If there is a security manager, this method first
1300      * calls its {@code checkMulticast} method with the
1301      * {@code mcastaddr} argument as its argument.
1302      *
1303      * @apiNote
1304      * The {@code mcastaddr} and {@code netIf} arguments should identify
1305      * a multicast group that was previously {@linkplain
1306      * #joinGroup(SocketAddress, NetworkInterface) joined} by
1307      * this {@code DatagramSocket}.
1308      * <p> It is possible to call this method several times to leave
1309      * multiple different multicast groups previously joined, or leave
1310      * the same group previously joined in multiple different networks.
1311      * However, if the socket is not a member of the specified group
1312      * in the specified network, an {@link IOException} will be
1313      * thrown.
1314      *
1315      * @param  mcastaddr is the multicast address to leave. This should
1316      *         contain the same IP address than that used for {@linkplain
1317      *         #joinGroup(SocketAddress, NetworkInterface) joining}
1318      *         the group.
1319      * @param  netIf specifies the local interface or {@code null} to defer
1320      *         to the interface set for outgoing multicast datagrams.
1321      *         If {@code null}, and no interface has been set, the behaviour
1322      *         is unspecified: any interface may be selected or the operation
1323      *         may fail with a {@code SocketException}.
1324      * @throws IOException if there is an error leaving or when the address
1325      *         is not a multicast address.
1326      * @throws SecurityException if a security manager exists and its
1327      *         {@code checkMulticast} method doesn't allow the operation.
1328      * @throws IllegalArgumentException if mcastaddr is {@code null} or is a
1329      *         SocketAddress subclass not supported by this socket.
1330      * @see    SecurityManager#checkMulticast(InetAddress)
1331      * @see    #joinGroup(SocketAddress, NetworkInterface)
1332      * @see    StandardSocketOptions#IP_MULTICAST_IF
1333      * @since  17
1334      */
1335     public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
1336             throws IOException {
1337         delegate().leaveGroup(mcastaddr, netIf);
1338     }
1339 
1340     // Temporary solution until JDK-8237352 is addressed
1341     private static final SocketAddress NO_DELEGATE = new SocketAddress() {};
1342 
1343     /**
1344      * Best effort to convert an {@link IOException}
1345      * into a {@link SocketException}.
1346      *
1347      * @param e an instance of {@link IOException}
1348      * @return an instance of {@link SocketException}
1349      */
1350     private static SocketException toSocketException(IOException e) {
1351         if (e instanceof SocketException)
1352             return (SocketException) e;
1353         Throwable cause = e.getCause();
1354         if (cause instanceof SocketException)
1355             return (SocketException) cause;
1356         SocketException se = new SocketException(e.getMessage());
1357         se.initCause(e);
1358         return se;
1359     }
1360 
1361     /**
1362      * Creates a delegate for the specific requested {@code type}. This method should
1363      * only be called by {@code DatagramSocket} and {@code MulticastSocket}
1364      * public constructors.
1365      *
1366      * @param bindaddr An address to bind to, or {@code null} if creating an unbound
1367      *                 socket.
1368      * @param type     This is either {@code MulticastSocket.class}, if the delegate needs
1369      *                 to support joining multicast groups, or {@code DatagramSocket.class},
1370      *                 if it doesn't. Typically, this will be {@code DatagramSocket.class}
1371      *                 when creating a delegate for {@code DatagramSocket}, and
1372      *                 {@code MulticastSocket.class} when creating a delegate for
1373      *                 {@code MulticastSocket}.
1374      * @param <T>      The target type for which the delegate is created.
1375      *                 This is either {@code java.net.DatagramSocket} or
1376      *                 {@code java.net.MulticastSocket}.
1377      * @return {@code null} if {@code bindaddr == NO_DELEGATE}, otherwise returns a
1378      * delegate for the requested {@code type}.
1379      * @throws SocketException if an exception occurs while creating or binding
1380      *                         the delegate.
1381      */
1382     static <T extends DatagramSocket> T createDelegate(SocketAddress bindaddr, Class<T> type)
1383             throws SocketException {
1384 
1385         // Temporary solution until JDK-8237352 is addressed
1386         if (bindaddr == NO_DELEGATE) return null;
1387 
1388         assert type == DatagramSocket.class || type == MulticastSocket.class;
1389         boolean multicast = (type == MulticastSocket.class);
1390         DatagramSocket delegate = null;
1391         boolean initialized = false;
1392         try {
1393             DatagramSocketImplFactory factory = DatagramSocket.factory;
1394             if (factory != null) {
1395                 // create legacy DatagramSocket delegate
1396                 DatagramSocketImpl impl = factory.createDatagramSocketImpl();
1397                 Objects.requireNonNull(impl,
1398                         "Implementation returned by installed DatagramSocketImplFactory is null");
1399                 delegate = new NetMulticastSocket(impl);
1400                 ((NetMulticastSocket) delegate).getImpl(); // ensure impl.create() is called.
1401             } else {
1402                 // create NIO adaptor
1403                 delegate = DefaultSelectorProvider.get()
1404                         .openUninterruptibleDatagramChannel()
1405                         .socket();
1406             }
1407 
1408             if (multicast) {
1409                 // set reuseaddress if multicasting
1410                 // (must be set before binding)
1411                 delegate.setReuseAddress(true);
1412             }
1413 
1414             if (bindaddr != null) {
1415                 // bind if needed
1416                 delegate.bind(bindaddr);
1417             }
1418 
1419             // enable broadcast if possible
1420             try {
1421                 delegate.setBroadcast(true);
1422             } catch (IOException ioe) {
1423             }
1424 
1425             initialized = true;
1426         } catch (IOException ioe) {
1427             throw toSocketException(ioe);
1428         } finally {
1429             // make sure the delegate is closed if anything
1430             // went wrong
1431             if (!initialized && delegate != null) {
1432                 delegate.close();
1433             }
1434         }
1435         @SuppressWarnings("unchecked")
1436         T result = (T) delegate;
1437         return result;
1438     }
1439 
1440 }
--- EOF ---