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