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 sun.security.util.SecurityConstants;
  29 
  30 import java.io.InputStream;
  31 import java.io.OutputStream;
  32 import java.io.IOException;
  33 import java.lang.invoke.MethodHandles;
  34 import java.lang.invoke.VarHandle;
  35 import java.nio.channels.SocketChannel;
  36 import java.util.Objects;
  37 import java.util.Set;
  38 import java.util.Collections;
  39 
  40 /**
  41  * This class implements client sockets (also called just
  42  * "sockets"). A socket is an endpoint for communication
  43  * between two machines.
  44  * <p>
  45  * The actual work of the socket is performed by an instance of the
  46  * {@code SocketImpl} class.
  47  *
  48  * <p> The {@code Socket} class defines convenience
  49  * methods to set and get several socket options. This class also
  50  * defines the {@link #setOption(SocketOption, Object) setOption}
  51  * and {@link #getOption(SocketOption) getOption} methods to set
  52  * and query socket options.
  53  * A {@code Socket} support the following options:
  54  * <blockquote>
  55  * <table class="striped">
  56  * <caption style="display:none">Socket options</caption>
  57  * <thead>
  58  *   <tr>
  59  *     <th scope="col">Option Name</th>
  60  *     <th scope="col">Description</th>
  61  *   </tr>
  62  * </thead>
  63  * <tbody>
  64  *   <tr>
  65  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>
  66  *     <td> The size of the socket send buffer </td>
  67  *   </tr>
  68  *   <tr>
  69  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
  70  *     <td> The size of the socket receive buffer </td>
  71  *   </tr>
  72  *   <tr>
  73  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_KEEPALIVE SO_KEEPALIVE} </th>
  74  *     <td> Keep connection alive </td>
  75  *   </tr>
  76  *   <tr>
  77  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
  78  *     <td> Re-use address </td>
  79  *   </tr>
  80  *   <tr>
  81  *     <th scope="row"> {@link java.net.StandardSocketOptions#SO_LINGER SO_LINGER} </th>
  82  *     <td> Linger on close if data is present (when configured in blocking mode
  83  *          only) </td>
  84  *   </tr>
  85  *   <tr>
  86  *     <th scope="row"> {@link java.net.StandardSocketOptions#TCP_NODELAY TCP_NODELAY} </th>
  87  *     <td> Disable the Nagle algorithm </td>
  88  *   </tr>
  89  * </tbody>
  90  * </table>
  91  * </blockquote>
  92  * Additional (implementation specific) options may also be supported.
  93  *
  94  * @see     java.net.SocketImpl
  95  * @see     java.nio.channels.SocketChannel
  96  * @since   1.0
  97  */
  98 public class Socket implements java.io.Closeable {
  99     /**
 100      * Various states of this socket.
 101      */
 102     private boolean created = false;
 103     private boolean bound = false;
 104     private boolean connected = false;
 105     private boolean closed = false;
 106     private Object closeLock = new Object();
 107     private boolean shutIn = false;
 108     private boolean shutOut = false;
 109 
 110     /**
 111      * The implementation of this Socket.
 112      */
 113     SocketImpl impl;
 114 
 115     /**
 116      * Socket input/output streams
 117      */
 118     private volatile InputStream in;
 119     private volatile OutputStream out;
 120     private static final VarHandle IN, OUT;
 121     static {
 122         try {
 123             MethodHandles.Lookup l = MethodHandles.lookup();
 124             IN = l.findVarHandle(Socket.class, "in", InputStream.class);
 125             OUT = l.findVarHandle(Socket.class, "out", OutputStream.class);
 126         } catch (Exception e) {
 127             throw new InternalError(e);
 128         }
 129     }
 130 
 131     /**
 132      * Creates an unconnected Socket.
 133      * <p>
 134      * If the application has specified a client socket implementation
 135      * factory, that factory's {@code createSocketImpl} method is called to
 136      * create the actual socket implementation. Otherwise a system-default
 137      * socket implementation is created.
 138      *
 139      * @since   1.1
 140      * @revised 1.4
 141      */
 142     public Socket() {
 143         setImpl();
 144     }
 145 
 146     /**
 147      * Creates an unconnected socket, specifying the type of proxy, if any,
 148      * that should be used regardless of any other settings.
 149      * <P>
 150      * If there is a security manager, its {@code checkConnect} method
 151      * is called with the proxy host address and port number
 152      * as its arguments. This could result in a SecurityException.
 153      * <P>
 154      * Examples:
 155      * <UL> <LI>{@code Socket s = new Socket(Proxy.NO_PROXY);} will create
 156      * a plain socket ignoring any other proxy configuration.</LI>
 157      * <LI>{@code Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080)));}
 158      * will create a socket connecting through the specified SOCKS proxy
 159      * server.</LI>
 160      * </UL>
 161      *
 162      * @param proxy a {@link java.net.Proxy Proxy} object specifying what kind
 163      *              of proxying should be used.
 164      * @throws IllegalArgumentException if the proxy is of an invalid type
 165      *          or {@code null}.
 166      * @throws SecurityException if a security manager is present and
 167      *                           permission to connect to the proxy is
 168      *                           denied.
 169      * @see java.net.ProxySelector
 170      * @see java.net.Proxy
 171      *
 172      * @since   1.5
 173      */
 174     public Socket(Proxy proxy) {
 175         // Create a copy of Proxy as a security measure
 176         if (proxy == null) {
 177             throw new IllegalArgumentException("Invalid Proxy");
 178         }
 179         Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY
 180                                           : sun.net.ApplicationProxy.create(proxy);
 181         Proxy.Type type = p.type();
 182         if (type == Proxy.Type.SOCKS || type == Proxy.Type.HTTP) {
 183             @SuppressWarnings("removal")
 184             SecurityManager security = System.getSecurityManager();
 185             InetSocketAddress epoint = (InetSocketAddress) p.address();
 186             if (epoint.getAddress() != null) {
 187                 checkAddress (epoint.getAddress(), "Socket");
 188             }
 189             if (security != null) {
 190                 if (epoint.isUnresolved())
 191                     epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort());
 192                 if (epoint.isUnresolved())
 193                     security.checkConnect(epoint.getHostName(), epoint.getPort());
 194                 else
 195                     security.checkConnect(epoint.getAddress().getHostAddress(),
 196                                   epoint.getPort());
 197             }
 198 
 199             // create a SOCKS or HTTP SocketImpl that delegates to a platform SocketImpl
 200             SocketImpl delegate = SocketImpl.createPlatformSocketImpl(false);
 201             impl = (type == Proxy.Type.SOCKS) ? new SocksSocketImpl(p, delegate)
 202                                               : new HttpConnectSocketImpl(p, delegate, this);
 203         } else {
 204             if (p == Proxy.NO_PROXY) {
 205                 // create a platform or custom SocketImpl for the DIRECT case
 206                 SocketImplFactory factory = Socket.factory;
 207                 if (factory == null) {
 208                     impl = SocketImpl.createPlatformSocketImpl(false);
 209                 } else {
 210                     impl = factory.createSocketImpl();
 211                 }
 212             } else
 213                 throw new IllegalArgumentException("Invalid Proxy");
 214         }
 215     }
 216 
 217     /**
 218      * Creates an unconnected Socket with a user-specified
 219      * SocketImpl.
 220      *
 221      * @param impl an instance of a <B>SocketImpl</B>
 222      * the subclass wishes to use on the Socket.
 223      *
 224      * @throws    SocketException if there is an error in the underlying protocol,
 225      * such as a TCP error.
 226      *
 227      * @throws SecurityException if {@code impl} is non-null and a security manager is set
 228      * and its {@code checkPermission} method doesn't allow {@code NetPermission("setSocketImpl")}.
 229      *
 230      * @since   1.1
 231      */
 232     protected Socket(SocketImpl impl) throws SocketException {
 233         checkPermission(impl);
 234         this.impl = impl;
 235     }
 236 
 237     private static Void checkPermission(SocketImpl impl) {
 238         if (impl == null) {
 239             return null;
 240         }
 241         @SuppressWarnings("removal")
 242         SecurityManager sm = System.getSecurityManager();
 243         if (sm != null) {
 244             sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION);
 245         }
 246         return null;
 247     }
 248 
 249     /**
 250      * Creates a stream socket and connects it to the specified port
 251      * number on the named host.
 252      * <p>
 253      * If the specified host is {@code null} it is the equivalent of
 254      * specifying the address as
 255      * {@link java.net.InetAddress#getByName InetAddress.getByName}{@code (null)}.
 256      * In other words, it is equivalent to specifying an address of the
 257      * loopback interface. </p>
 258      * <p>
 259      * If the application has specified a client socket implementation
 260      * factory, that factory's {@code createSocketImpl} method is called to
 261      * create the actual socket implementation. Otherwise a system-default
 262      * socket implementation is created.
 263      * <p>
 264      * If there is a security manager, its
 265      * {@code checkConnect} method is called
 266      * with the host address and {@code port}
 267      * as its arguments. This could result in a SecurityException.
 268      *
 269      * @param      host   the host name, or {@code null} for the loopback address.
 270      * @param      port   the port number.
 271      *
 272      * @throws     UnknownHostException if the IP address of
 273      * the host could not be determined.
 274      *
 275      * @throws     IOException  if an I/O error occurs when creating the socket.
 276      * @throws     SecurityException  if a security manager exists and its
 277      *             {@code checkConnect} method doesn't allow the operation.
 278      * @throws     IllegalArgumentException if the port parameter is outside
 279      *             the specified range of valid port values, which is between
 280      *             0 and 65535, inclusive.
 281      * @see        java.net.SocketImpl
 282      * @see        SecurityManager#checkConnect
 283      */
 284     public Socket(String host, int port)
 285         throws UnknownHostException, IOException
 286     {
 287         this(host != null ? new InetSocketAddress(host, port) :
 288              new InetSocketAddress(InetAddress.getByName(null), port),
 289              (SocketAddress) null, true);
 290     }
 291 
 292     /**
 293      * Creates a stream socket and connects it to the specified port
 294      * number at the specified IP address.
 295      * <p>
 296      * If the application has specified a client socket implementation
 297      * factory, that factory's {@code createSocketImpl} method is called to
 298      * create the actual socket implementation. Otherwise a system-default
 299      * socket implementation is created.
 300      * <p>
 301      * If there is a security manager, its
 302      * {@code checkConnect} method is called
 303      * with the host address and {@code port}
 304      * as its arguments. This could result in a SecurityException.
 305      *
 306      * @param      address   the IP address.
 307      * @param      port      the port number.
 308      * @throws     IOException  if an I/O error occurs when creating the socket.
 309      * @throws     SecurityException  if a security manager exists and its
 310      *             {@code checkConnect} method doesn't allow the operation.
 311      * @throws     IllegalArgumentException if the port parameter is outside
 312      *             the specified range of valid port values, which is between
 313      *             0 and 65535, inclusive.
 314      * @throws     NullPointerException if {@code address} is null.
 315      * @see        java.net.SocketImpl
 316      * @see        SecurityManager#checkConnect
 317      */
 318     public Socket(InetAddress address, int port) throws IOException {
 319         this(address != null ? new InetSocketAddress(address, port) : null,
 320              (SocketAddress) null, true);
 321     }
 322 
 323     /**
 324      * Creates a socket and connects it to the specified remote host on
 325      * the specified remote port. The Socket will also bind() to the local
 326      * address and port supplied.
 327      * <p>
 328      * If the specified host is {@code null} it is the equivalent of
 329      * specifying the address as
 330      * {@link java.net.InetAddress#getByName InetAddress.getByName}{@code (null)}.
 331      * In other words, it is equivalent to specifying an address of the
 332      * loopback interface. </p>
 333      * <p>
 334      * A local port number of {@code zero} will let the system pick up a
 335      * free port in the {@code bind} operation.</p>
 336      * <p>
 337      * If there is a security manager, its
 338      * {@code checkConnect} method is called
 339      * with the host address and {@code port}
 340      * as its arguments. This could result in a SecurityException.
 341      *
 342      * @param host the name of the remote host, or {@code null} for the loopback address.
 343      * @param port the remote port
 344      * @param localAddr the local address the socket is bound to, or
 345      *        {@code null} for the {@code anyLocal} address.
 346      * @param localPort the local port the socket is bound to, or
 347      *        {@code zero} for a system selected free port.
 348      * @throws     IOException  if an I/O error occurs when creating the socket.
 349      * @throws     SecurityException  if a security manager exists and its
 350      *             {@code checkConnect} method doesn't allow the connection
 351      *             to the destination, or if its {@code checkListen} method
 352      *             doesn't allow the bind to the local port.
 353      * @throws     IllegalArgumentException if the port parameter or localPort
 354      *             parameter is outside the specified range of valid port values,
 355      *             which is between 0 and 65535, inclusive.
 356      * @see        SecurityManager#checkConnect
 357      * @since   1.1
 358      */
 359     public Socket(String host, int port, InetAddress localAddr,
 360                   int localPort) throws IOException {
 361         this(host != null ? new InetSocketAddress(host, port) :
 362                new InetSocketAddress(InetAddress.getByName(null), port),
 363              new InetSocketAddress(localAddr, localPort), true);
 364     }
 365 
 366     /**
 367      * Creates a socket and connects it to the specified remote address on
 368      * the specified remote port. The Socket will also bind() to the local
 369      * address and port supplied.
 370      * <p>
 371      * If the specified local address is {@code null} it is the equivalent of
 372      * specifying the address as the AnyLocal address
 373      * (see {@link java.net.InetAddress#isAnyLocalAddress InetAddress.isAnyLocalAddress}{@code ()}).
 374      * <p>
 375      * A local port number of {@code zero} will let the system pick up a
 376      * free port in the {@code bind} operation.</p>
 377      * <p>
 378      * If there is a security manager, its
 379      * {@code checkConnect} method is called
 380      * with the host address and {@code port}
 381      * as its arguments. This could result in a SecurityException.
 382      *
 383      * @param address the remote address
 384      * @param port the remote port
 385      * @param localAddr the local address the socket is bound to, or
 386      *        {@code null} for the {@code anyLocal} address.
 387      * @param localPort the local port the socket is bound to or
 388      *        {@code zero} for a system selected free port.
 389      * @throws     IOException  if an I/O error occurs when creating the socket.
 390      * @throws     SecurityException  if a security manager exists and its
 391      *             {@code checkConnect} method doesn't allow the connection
 392      *             to the destination, or if its {@code checkListen} method
 393      *             doesn't allow the bind to the local port.
 394      * @throws     IllegalArgumentException if the port parameter or localPort
 395      *             parameter is outside the specified range of valid port values,
 396      *             which is between 0 and 65535, inclusive.
 397      * @throws     NullPointerException if {@code address} is null.
 398      * @see        SecurityManager#checkConnect
 399      * @since   1.1
 400      */
 401     public Socket(InetAddress address, int port, InetAddress localAddr,
 402                   int localPort) throws IOException {
 403         this(address != null ? new InetSocketAddress(address, port) : null,
 404              new InetSocketAddress(localAddr, localPort), true);
 405     }
 406 
 407     /**
 408      * Creates a stream socket and connects it to the specified port
 409      * number on the named host.
 410      * <p>
 411      * If the specified host is {@code null} it is the equivalent of
 412      * specifying the address as
 413      * {@link java.net.InetAddress#getByName InetAddress.getByName}{@code (null)}.
 414      * In other words, it is equivalent to specifying an address of the
 415      * loopback interface. </p>
 416      * <p>
 417      * If the stream argument is {@code true}, this creates a
 418      * stream socket. If the stream argument is {@code false}, it
 419      * creates a datagram socket.
 420      * <p>
 421      * If the application has specified a client socket implementation
 422      * factory, that factory's {@code createSocketImpl} method is called to
 423      * create the actual socket implementation. Otherwise a system-default
 424      * socket implementation is created.
 425      * <p>
 426      * If there is a security manager, its
 427      * {@code checkConnect} method is called
 428      * with the host address and {@code port}
 429      * as its arguments. This could result in a SecurityException.
 430      * <p>
 431      * If a UDP socket is used, TCP/IP related socket options will not apply.
 432      *
 433      * @param      host     the host name, or {@code null} for the loopback address.
 434      * @param      port     the port number.
 435      * @param      stream   a {@code boolean} indicating whether this is
 436      *                      a stream socket or a datagram socket.
 437      * @throws     IOException  if an I/O error occurs when creating the socket.
 438      * @throws     SecurityException  if a security manager exists and its
 439      *             {@code checkConnect} method doesn't allow the operation.
 440      * @throws     IllegalArgumentException if the port parameter is outside
 441      *             the specified range of valid port values, which is between
 442      *             0 and 65535, inclusive.
 443      * @see        java.net.SocketImpl
 444      * @see        SecurityManager#checkConnect
 445      * @deprecated Use DatagramSocket instead for UDP transport.
 446      */
 447     @Deprecated
 448     public Socket(String host, int port, boolean stream) throws IOException {
 449         this(host != null ? new InetSocketAddress(host, port) :
 450                new InetSocketAddress(InetAddress.getByName(null), port),
 451              (SocketAddress) null, stream);
 452     }
 453 
 454     /**
 455      * Creates a socket and connects it to the specified port number at
 456      * the specified IP address.
 457      * <p>
 458      * If the stream argument is {@code true}, this creates a
 459      * stream socket. If the stream argument is {@code false}, it
 460      * creates a datagram socket.
 461      * <p>
 462      * If the application has specified a client socket implementation
 463      * factory, that factory's {@code createSocketImpl} method is called to
 464      * create the actual socket implementation. Otherwise a system-default
 465      * socket implementation is created.
 466      *
 467      * <p>If there is a security manager, its
 468      * {@code checkConnect} method is called
 469      * with {@code host.getHostAddress()} and {@code port}
 470      * as its arguments. This could result in a SecurityException.
 471      * <p>
 472      * If UDP socket is used, TCP/IP related socket options will not apply.
 473      *
 474      * @param      host     the IP address.
 475      * @param      port      the port number.
 476      * @param      stream    if {@code true}, create a stream socket;
 477      *                       otherwise, create a datagram socket.
 478      * @throws     IOException  if an I/O error occurs when creating the socket.
 479      * @throws     SecurityException  if a security manager exists and its
 480      *             {@code checkConnect} method doesn't allow the operation.
 481      * @throws     IllegalArgumentException if the port parameter is outside
 482      *             the specified range of valid port values, which is between
 483      *             0 and 65535, inclusive.
 484      * @throws     NullPointerException if {@code host} is null.
 485      * @see        java.net.SocketImpl
 486      * @see        SecurityManager#checkConnect
 487      * @deprecated Use DatagramSocket instead for UDP transport.
 488      */
 489     @Deprecated
 490     public Socket(InetAddress host, int port, boolean stream) throws IOException {
 491         this(host != null ? new InetSocketAddress(host, port) : null,
 492              new InetSocketAddress(0), stream);
 493     }
 494 
 495     private Socket(SocketAddress address, SocketAddress localAddr,
 496                    boolean stream) throws IOException {
 497         setImpl();
 498 
 499         // backward compatibility
 500         if (address == null)
 501             throw new NullPointerException();
 502 
 503         try {
 504             createImpl(stream);
 505             if (localAddr != null)
 506                 bind(localAddr);
 507             connect(address);
 508         } catch (IOException | IllegalArgumentException | SecurityException e) {
 509             try {
 510                 close();
 511             } catch (IOException ce) {
 512                 e.addSuppressed(ce);
 513             }
 514             throw e;
 515         }
 516     }
 517 
 518     /**
 519      * Creates the socket implementation.
 520      *
 521      * @param stream a {@code boolean} value : {@code true} for a TCP socket,
 522      *               {@code false} for UDP.
 523      * @throws SocketException if creation fails
 524      * @since 1.4
 525      */
 526      void createImpl(boolean stream) throws SocketException {
 527         if (impl == null)
 528             setImpl();
 529         try {
 530             impl.create(stream);
 531             created = true;
 532         } catch (IOException e) {
 533             throw new SocketException(e.getMessage());
 534         }
 535     }
 536 
 537     void setImpl(SocketImpl si) {
 538          impl = si;
 539     }
 540 
 541     /**
 542      * Sets impl to the system-default type of SocketImpl.
 543      * @since 1.4
 544      */
 545     void setImpl() {
 546         SocketImplFactory factory = Socket.factory;
 547         if (factory != null) {
 548             impl = factory.createSocketImpl();
 549         } else {
 550             // create a SOCKS SocketImpl that delegates to a platform SocketImpl
 551             SocketImpl delegate = SocketImpl.createPlatformSocketImpl(false);
 552             impl = new SocksSocketImpl(delegate);
 553         }
 554     }
 555 
 556     /**
 557      * Get the {@code SocketImpl} attached to this socket, creating
 558      * it if necessary.
 559      *
 560      * @return  the {@code SocketImpl} attached to that ServerSocket.
 561      * @throws SocketException if creation fails
 562      * @since 1.4
 563      */
 564     SocketImpl getImpl() throws SocketException {
 565         if (!created)
 566             createImpl(true);
 567         return impl;
 568     }
 569 
 570     /**
 571      * Connects this socket to the server.
 572      *
 573      * @param   endpoint the {@code SocketAddress}
 574      * @throws  IOException if an error occurs during the connection
 575      * @throws  java.nio.channels.IllegalBlockingModeException
 576      *          if this socket has an associated channel,
 577      *          and the channel is in non-blocking mode
 578      * @throws  IllegalArgumentException if endpoint is null or is a
 579      *          SocketAddress subclass not supported by this socket
 580      * @since 1.4
 581      */
 582     public void connect(SocketAddress endpoint) throws IOException {
 583         connect(endpoint, 0);
 584     }
 585 
 586     /**
 587      * Connects this socket to the server with a specified timeout value.
 588      * A timeout of zero is interpreted as an infinite timeout. The connection
 589      * will then block until established or an error occurs.
 590      *
 591      * @param   endpoint the {@code SocketAddress}
 592      * @param   timeout  the timeout value to be used in milliseconds.
 593      * @throws  IOException if an error occurs during the connection
 594      * @throws  SocketTimeoutException if timeout expires before connecting
 595      * @throws  java.nio.channels.IllegalBlockingModeException
 596      *          if this socket has an associated channel,
 597      *          and the channel is in non-blocking mode
 598      * @throws  IllegalArgumentException if endpoint is null or is a
 599      *          SocketAddress subclass not supported by this socket, or
 600      *          if {@code timeout} is negative
 601      * @since 1.4
 602      */
 603     public void connect(SocketAddress endpoint, int timeout) throws IOException {
 604         if (endpoint == null)
 605             throw new IllegalArgumentException("connect: The address can't be null");
 606 
 607         if (timeout < 0)
 608           throw new IllegalArgumentException("connect: timeout can't be negative");
 609 
 610         if (isClosed())
 611             throw new SocketException("Socket is closed");
 612 
 613         if (isConnected())
 614             throw new SocketException("already connected");
 615 
 616         if (!(endpoint instanceof InetSocketAddress epoint))
 617             throw new IllegalArgumentException("Unsupported address type");
 618 
 619         InetAddress addr = epoint.getAddress ();
 620         int port = epoint.getPort();
 621         checkAddress(addr, "connect");
 622 
 623         @SuppressWarnings("removal")
 624         SecurityManager security = System.getSecurityManager();
 625         if (security != null) {
 626             if (epoint.isUnresolved())
 627                 security.checkConnect(epoint.getHostName(), port);
 628             else
 629                 security.checkConnect(addr.getHostAddress(), port);
 630         }
 631         if (!created)
 632             createImpl(true);
 633         impl.connect(epoint, timeout);
 634         connected = true;
 635         /*
 636          * If the socket was not bound before the connect, it is now because
 637          * the kernel will have picked an ephemeral port & a local address
 638          */
 639         bound = true;
 640     }
 641 
 642     /**
 643      * Binds the socket to a local address.
 644      * <P>
 645      * If the address is {@code null}, then the system will pick up
 646      * an ephemeral port and a valid local address to bind the socket.
 647      *
 648      * @param   bindpoint the {@code SocketAddress} to bind to
 649      * @throws  IOException if the bind operation fails, or if the socket
 650      *                     is already bound.
 651      * @throws  IllegalArgumentException if bindpoint is a
 652      *          SocketAddress subclass not supported by this socket
 653      * @throws  SecurityException  if a security manager exists and its
 654      *          {@code checkListen} method doesn't allow the bind
 655      *          to the local port.
 656      *
 657      * @since   1.4
 658      * @see #isBound
 659      */
 660     public void bind(SocketAddress bindpoint) throws IOException {
 661         if (isClosed())
 662             throw new SocketException("Socket is closed");
 663         if (isBound())
 664             throw new SocketException("Already bound");
 665 
 666         if (bindpoint != null && (!(bindpoint instanceof InetSocketAddress)))
 667             throw new IllegalArgumentException("Unsupported address type");
 668         InetSocketAddress epoint = (InetSocketAddress) bindpoint;
 669         if (epoint != null && epoint.isUnresolved())
 670             throw new SocketException("Unresolved address");
 671         if (epoint == null) {
 672             epoint = new InetSocketAddress(0);
 673         }
 674         InetAddress addr = epoint.getAddress();
 675         int port = epoint.getPort();
 676         checkAddress (addr, "bind");
 677         @SuppressWarnings("removal")
 678         SecurityManager security = System.getSecurityManager();
 679         if (security != null) {
 680             security.checkListen(port);
 681         }
 682         getImpl().bind (addr, port);
 683         bound = true;
 684     }
 685 
 686     private void checkAddress (InetAddress addr, String op) {
 687         if (addr == null) {
 688             return;
 689         }
 690         if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
 691             throw new IllegalArgumentException(op + ": invalid address type");
 692         }
 693     }
 694 
 695     /**
 696      * set the flags after an accept() call.
 697      */
 698     final void postAccept() {
 699         connected = true;
 700         created = true;
 701         bound = true;
 702     }
 703 
 704     /**
 705      * Returns the address to which the socket is connected.
 706      * <p>
 707      * If the socket was connected prior to being {@link #close closed},
 708      * then this method will continue to return the connected address
 709      * after the socket is closed.
 710      *
 711      * @return  the remote IP address to which this socket is connected,
 712      *          or {@code null} if the socket is not connected.
 713      */
 714     public InetAddress getInetAddress() {
 715         if (!isConnected())
 716             return null;
 717         try {
 718             return getImpl().getInetAddress();
 719         } catch (SocketException e) {
 720         }
 721         return null;
 722     }
 723 
 724     /**
 725      * Gets the local address to which the socket is bound.
 726      * <p>
 727      * If there is a security manager set, its {@code checkConnect} method is
 728      * called with the local address and {@code -1} as its arguments to see
 729      * if the operation is allowed. If the operation is not allowed,
 730      * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
 731      *
 732      * @return the local address to which the socket is bound,
 733      *         the loopback address if denied by the security manager, or
 734      *         the wildcard address if the socket is closed or not bound yet.
 735      * @since   1.1
 736      *
 737      * @see SecurityManager#checkConnect
 738      */
 739     public InetAddress getLocalAddress() {
 740         // This is for backward compatibility
 741         if (!isBound())
 742             return InetAddress.anyLocalAddress();
 743         InetAddress in = null;
 744         try {
 745             in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
 746             @SuppressWarnings("removal")
 747             SecurityManager sm = System.getSecurityManager();
 748             if (sm != null)
 749                 sm.checkConnect(in.getHostAddress(), -1);
 750             if (in.isAnyLocalAddress()) {
 751                 in = InetAddress.anyLocalAddress();
 752             }
 753         } catch (SecurityException e) {
 754             in = InetAddress.getLoopbackAddress();
 755         } catch (Exception e) {
 756             in = InetAddress.anyLocalAddress(); // "0.0.0.0"
 757         }
 758         return in;
 759     }
 760 
 761     /**
 762      * Returns the remote port number to which this socket is connected.
 763      * <p>
 764      * If the socket was connected prior to being {@link #close closed},
 765      * then this method will continue to return the connected port number
 766      * after the socket is closed.
 767      *
 768      * @return  the remote port number to which this socket is connected, or
 769      *          0 if the socket is not connected yet.
 770      */
 771     public int getPort() {
 772         if (!isConnected())
 773             return 0;
 774         try {
 775             return getImpl().getPort();
 776         } catch (SocketException e) {
 777             // Shouldn't happen as we're connected
 778         }
 779         return -1;
 780     }
 781 
 782     /**
 783      * Returns the local port number to which this socket is bound.
 784      * <p>
 785      * If the socket was bound prior to being {@link #close closed},
 786      * then this method will continue to return the local port number
 787      * after the socket is closed.
 788      *
 789      * @return  the local port number to which this socket is bound or -1
 790      *          if the socket is not bound yet.
 791      */
 792     public int getLocalPort() {
 793         if (!isBound())
 794             return -1;
 795         try {
 796             return getImpl().getLocalPort();
 797         } catch(SocketException e) {
 798             // shouldn't happen as we're bound
 799         }
 800         return -1;
 801     }
 802 
 803     /**
 804      * Returns the address of the endpoint this socket is connected to, or
 805      * {@code null} if it is unconnected.
 806      * <p>
 807      * If the socket was connected prior to being {@link #close closed},
 808      * then this method will continue to return the connected address
 809      * after the socket is closed.
 810      *
 811      * @return a {@code SocketAddress} representing the remote endpoint of this
 812      *         socket, or {@code null} if it is not connected yet.
 813      * @see #getInetAddress()
 814      * @see #getPort()
 815      * @see #connect(SocketAddress, int)
 816      * @see #connect(SocketAddress)
 817      * @since 1.4
 818      */
 819     public SocketAddress getRemoteSocketAddress() {
 820         if (!isConnected())
 821             return null;
 822         return new InetSocketAddress(getInetAddress(), getPort());
 823     }
 824 
 825     /**
 826      * Returns the address of the endpoint this socket is bound to.
 827      * <p>
 828      * If a socket bound to an endpoint represented by an
 829      * {@code InetSocketAddress } is {@link #close closed},
 830      * then this method will continue to return an {@code InetSocketAddress}
 831      * after the socket is closed. In that case the returned
 832      * {@code InetSocketAddress}'s address is the
 833      * {@link InetAddress#isAnyLocalAddress wildcard} address
 834      * and its port is the local port that it was bound to.
 835      * <p>
 836      * If there is a security manager set, its {@code checkConnect} method is
 837      * called with the local address and {@code -1} as its arguments to see
 838      * if the operation is allowed. If the operation is not allowed,
 839      * a {@code SocketAddress} representing the
 840      * {@link InetAddress#getLoopbackAddress loopback} address and the local
 841      * port to which this socket is bound is returned.
 842      *
 843      * @return a {@code SocketAddress} representing the local endpoint of
 844      *         this socket, or a {@code SocketAddress} representing the
 845      *         loopback address if denied by the security manager, or
 846      *         {@code null} if the socket is not bound yet.
 847      *
 848      * @see #getLocalAddress()
 849      * @see #getLocalPort()
 850      * @see #bind(SocketAddress)
 851      * @see SecurityManager#checkConnect
 852      * @since 1.4
 853      */
 854 
 855     public SocketAddress getLocalSocketAddress() {
 856         if (!isBound())
 857             return null;
 858         return new InetSocketAddress(getLocalAddress(), getLocalPort());
 859     }
 860 
 861     /**
 862      * Returns the unique {@link java.nio.channels.SocketChannel SocketChannel}
 863      * object associated with this socket, if any.
 864      *
 865      * <p> A socket will have a channel if, and only if, the channel itself was
 866      * created via the {@link java.nio.channels.SocketChannel#open
 867      * SocketChannel.open} or {@link
 868      * java.nio.channels.ServerSocketChannel#accept ServerSocketChannel.accept}
 869      * methods.
 870      *
 871      * @return  the socket channel associated with this socket,
 872      *          or {@code null} if this socket was not created
 873      *          for a channel
 874      *
 875      * @since 1.4
 876      */
 877     public SocketChannel getChannel() {
 878         return null;
 879     }
 880 
 881     /**
 882      * Returns an input stream for this socket.
 883      *
 884      * <p> If this socket has an associated channel then the resulting input
 885      * stream delegates all of its operations to the channel.  If the channel
 886      * is in non-blocking mode then the input stream's {@code read} operations
 887      * will throw an {@link java.nio.channels.IllegalBlockingModeException}.
 888      *
 889      * <p>Under abnormal conditions the underlying connection may be
 890      * broken by the remote host or the network software (for example
 891      * a connection reset in the case of TCP connections). When a
 892      * broken connection is detected by the network software the
 893      * following applies to the returned input stream :-
 894      *
 895      * <ul>
 896      *
 897      *   <li><p>The network software may discard bytes that are buffered
 898      *   by the socket. Bytes that aren't discarded by the network
 899      *   software can be read using {@link java.io.InputStream#read read}.
 900      *
 901      *   <li><p>If there are no bytes buffered on the socket, or all
 902      *   buffered bytes have been consumed by
 903      *   {@link java.io.InputStream#read read}, then all subsequent
 904      *   calls to {@link java.io.InputStream#read read} will throw an
 905      *   {@link java.io.IOException IOException}.
 906      *
 907      *   <li><p>If there are no bytes buffered on the socket, and the
 908      *   socket has not been closed using {@link #close close}, then
 909      *   {@link java.io.InputStream#available available} will
 910      *   return {@code 0}.
 911      *
 912      * </ul>
 913      *
 914      * <p> Closing the returned {@link java.io.InputStream InputStream}
 915      * will close the associated socket.
 916      *
 917      * @return     an input stream for reading bytes from this socket.
 918      * @throws     IOException  if an I/O error occurs when creating the
 919      *             input stream, the socket is closed, the socket is
 920      *             not connected, or the socket input has been shutdown
 921      *             using {@link #shutdownInput()}
 922      *
 923      * @revised 1.4
 924      */
 925     public InputStream getInputStream() throws IOException {
 926         if (isClosed())
 927             throw new SocketException("Socket is closed");
 928         if (!isConnected())
 929             throw new SocketException("Socket is not connected");
 930         if (isInputShutdown())
 931             throw new SocketException("Socket input is shutdown");
 932         InputStream in = this.in;
 933         if (in == null) {
 934             // wrap the input stream so that the close method closes this socket
 935             in = new SocketInputStream(this, impl.getInputStream());
 936             if (!IN.compareAndSet(this, null, in)) {
 937                 in = this.in;
 938             }
 939         }
 940         return in;
 941     }
 942 
 943     /**
 944      * An InputStream that delegates read/available operations to an underlying
 945      * input stream. The close method is overridden to close the Socket.
 946      *
 947      * This class is instrumented by Java Flight Recorder (JFR) to get socket
 948      * I/O events.
 949      */
 950     private static class SocketInputStream extends InputStream {
 951         private final Socket parent;
 952         private final InputStream in;
 953 
 954         SocketInputStream(Socket parent, InputStream in) {
 955             this.parent = parent;
 956             this.in = in;
 957         }
 958         @Override
 959         public int read() throws IOException {
 960             byte[] a = new byte[1];
 961             int n = read(a, 0, 1);
 962             return (n > 0) ? (a[0] & 0xff) : -1;
 963         }
 964         @Override
 965         public int read(byte[] b, int off, int len) throws IOException {
 966             return in.read(b, off, len);
 967         }
 968         @Override
 969         public int available() throws IOException {
 970             return in.available();
 971         }
 972 
 973         @Override
 974         public void close() throws IOException {
 975             parent.close();
 976         }
 977     }
 978 
 979     /**
 980      * Returns an output stream for this socket.
 981      *
 982      * <p> If this socket has an associated channel then the resulting output
 983      * stream delegates all of its operations to the channel.  If the channel
 984      * is in non-blocking mode then the output stream's {@code write}
 985      * operations will throw an {@link
 986      * java.nio.channels.IllegalBlockingModeException}.
 987      *
 988      * <p> Closing the returned {@link java.io.OutputStream OutputStream}
 989      * will close the associated socket.
 990      *
 991      * @return     an output stream for writing bytes to this socket.
 992      * @throws     IOException  if an I/O error occurs when creating the
 993      *               output stream or if the socket is not connected.
 994      * @revised 1.4
 995      */
 996     public OutputStream getOutputStream() throws IOException {
 997         if (isClosed())
 998             throw new SocketException("Socket is closed");
 999         if (!isConnected())
1000             throw new SocketException("Socket is not connected");
1001         if (isOutputShutdown())
1002             throw new SocketException("Socket output is shutdown");
1003         OutputStream out = this.out;
1004         if (out == null) {
1005             // wrap the output stream so that the close method closes this socket
1006             out = new SocketOutputStream(this, impl.getOutputStream());
1007             if (!OUT.compareAndSet(this, null, out)) {
1008                 out = this.out;
1009             }
1010         }
1011         return out;
1012     }
1013 
1014     /**
1015      * An OutputStream that delegates write operations to an underlying output
1016      * stream. The close method is overridden to close the Socket.
1017      *
1018      * This class is instrumented by Java Flight Recorder (JFR) to get socket
1019      * I/O events.
1020      */
1021     private static class SocketOutputStream extends OutputStream {
1022         private final Socket parent;
1023         private final OutputStream out;
1024         SocketOutputStream(Socket parent, OutputStream out) {
1025             this.parent = parent;
1026             this.out = out;
1027         }
1028         @Override
1029         public void write(int b) throws IOException {
1030             byte[] a = new byte[] { (byte) b };
1031             write(a, 0, 1);
1032         }
1033         @Override
1034         public void write(byte[] b, int off, int len) throws IOException {
1035             out.write(b, off, len);
1036         }
1037 
1038         @Override
1039         public void close() throws IOException {
1040             parent.close();
1041         }
1042     }
1043 
1044     /**
1045      * Enable/disable {@link SocketOptions#TCP_NODELAY TCP_NODELAY}
1046      * (disable/enable Nagle's algorithm).
1047      *
1048      * @param on {@code true} to enable TCP_NODELAY,
1049      * {@code false} to disable.
1050      *
1051      * @throws    SocketException if there is an error
1052      * in the underlying protocol, such as a TCP error.
1053      *
1054      * @since   1.1
1055      *
1056      * @see #getTcpNoDelay()
1057      */
1058     public void setTcpNoDelay(boolean on) throws SocketException {
1059         if (isClosed())
1060             throw new SocketException("Socket is closed");
1061         getImpl().setOption(SocketOptions.TCP_NODELAY, Boolean.valueOf(on));
1062     }
1063 
1064     /**
1065      * Tests if {@link SocketOptions#TCP_NODELAY TCP_NODELAY} is enabled.
1066      *
1067      * @return a {@code boolean} indicating whether or not
1068      *         {@link SocketOptions#TCP_NODELAY TCP_NODELAY} is enabled.
1069      * @throws    SocketException if there is an error
1070      * in the underlying protocol, such as a TCP error.
1071      * @since   1.1
1072      * @see #setTcpNoDelay(boolean)
1073      */
1074     public boolean getTcpNoDelay() throws SocketException {
1075         if (isClosed())
1076             throw new SocketException("Socket is closed");
1077         return ((Boolean) getImpl().getOption(SocketOptions.TCP_NODELAY)).booleanValue();
1078     }
1079 
1080     /**
1081      * Enable/disable {@link SocketOptions#SO_LINGER SO_LINGER} with the
1082      * specified linger time in seconds. The maximum timeout value is platform
1083      * specific.
1084      *
1085      * The setting only affects socket close.
1086      *
1087      * @param on     whether or not to linger on.
1088      * @param linger how long to linger for, if on is true.
1089      * @throws    SocketException if there is an error
1090      * in the underlying protocol, such as a TCP error.
1091      * @throws    IllegalArgumentException if the linger value is negative.
1092      * @since 1.1
1093      * @see #getSoLinger()
1094      */
1095     public void setSoLinger(boolean on, int linger) throws SocketException {
1096         if (isClosed())
1097             throw new SocketException("Socket is closed");
1098         if (!on) {
1099             getImpl().setOption(SocketOptions.SO_LINGER, on);
1100         } else {
1101             if (linger < 0) {
1102                 throw new IllegalArgumentException("invalid value for SO_LINGER");
1103             }
1104             if (linger > 65535)
1105                 linger = 65535;
1106             getImpl().setOption(SocketOptions.SO_LINGER, linger);
1107         }
1108     }
1109 
1110     /**
1111      * Returns setting for {@link SocketOptions#SO_LINGER SO_LINGER}.
1112      * -1 returns implies that the
1113      * option is disabled.
1114      *
1115      * The setting only affects socket close.
1116      *
1117      * @return the setting for {@link SocketOptions#SO_LINGER SO_LINGER}.
1118      * @throws    SocketException if there is an error
1119      * in the underlying protocol, such as a TCP error.
1120      * @since   1.1
1121      * @see #setSoLinger(boolean, int)
1122      */
1123     public int getSoLinger() throws SocketException {
1124         if (isClosed())
1125             throw new SocketException("Socket is closed");
1126         Object o = getImpl().getOption(SocketOptions.SO_LINGER);
1127         if (o instanceof Integer) {
1128             return ((Integer) o).intValue();
1129         } else {
1130             return -1;
1131         }
1132     }
1133 
1134     /**
1135      * Send one byte of urgent data on the socket. The byte to be sent is the lowest eight
1136      * bits of the data parameter. The urgent byte is
1137      * sent after any preceding writes to the socket OutputStream
1138      * and before any future writes to the OutputStream.
1139      * @param data The byte of data to send
1140      * @throws    IOException if there is an error
1141      *  sending the data.
1142      * @since 1.4
1143      */
1144     public void sendUrgentData (int data) throws IOException  {
1145         if (!getImpl().supportsUrgentData ()) {
1146             throw new SocketException ("Urgent data not supported");
1147         }
1148         getImpl().sendUrgentData (data);
1149     }
1150 
1151     /**
1152      * Enable/disable {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE}
1153      * (receipt of TCP urgent data)
1154      *
1155      * By default, this option is disabled and TCP urgent data received on a
1156      * socket is silently discarded. If the user wishes to receive urgent data, then
1157      * this option must be enabled. When enabled, urgent data is received
1158      * inline with normal data.
1159      * <p>
1160      * Note, only limited support is provided for handling incoming urgent
1161      * data. In particular, no notification of incoming urgent data is provided
1162      * and there is no capability to distinguish between normal data and urgent
1163      * data unless provided by a higher level protocol.
1164      *
1165      * @param on {@code true} to enable
1166      *           {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE},
1167      *           {@code false} to disable.
1168      *
1169      * @throws    SocketException if there is an error
1170      * in the underlying protocol, such as a TCP error.
1171      *
1172      * @since   1.4
1173      *
1174      * @see #getOOBInline()
1175      */
1176     public void setOOBInline(boolean on) throws SocketException {
1177         if (isClosed())
1178             throw new SocketException("Socket is closed");
1179         getImpl().setOption(SocketOptions.SO_OOBINLINE, Boolean.valueOf(on));
1180     }
1181 
1182     /**
1183      * Tests if {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE} is enabled.
1184      *
1185      * @return a {@code boolean} indicating whether or not
1186      *         {@link SocketOptions#SO_OOBINLINE SO_OOBINLINE} is enabled.
1187      *
1188      * @throws    SocketException if there is an error
1189      * in the underlying protocol, such as a TCP error.
1190      * @since   1.4
1191      * @see #setOOBInline(boolean)
1192      */
1193     public boolean getOOBInline() throws SocketException {
1194         if (isClosed())
1195             throw new SocketException("Socket is closed");
1196         return ((Boolean) getImpl().getOption(SocketOptions.SO_OOBINLINE)).booleanValue();
1197     }
1198 
1199     /**
1200      *  Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}
1201      *  with the specified timeout, in milliseconds. With this option set
1202      *  to a positive timeout value, a read() call on the InputStream associated with
1203      *  this Socket will block for only this amount of time.  If the timeout
1204      *  expires, a <B>java.net.SocketTimeoutException</B> is raised, though the
1205      *  Socket is still valid. A timeout of zero is interpreted as an infinite timeout.
1206      *  The option <B>must</B> be enabled prior to entering the blocking operation
1207      *  to have effect.
1208      *
1209      * @param timeout the specified timeout, in milliseconds.
1210      * @throws  SocketException if there is an error in the underlying protocol,
1211      *          such as a TCP error
1212      * @throws  IllegalArgumentException if {@code timeout} is negative
1213      * @since   1.1
1214      * @see #getSoTimeout()
1215      */
1216     public synchronized void setSoTimeout(int timeout) throws SocketException {
1217         if (isClosed())
1218             throw new SocketException("Socket is closed");
1219         if (timeout < 0)
1220           throw new IllegalArgumentException("timeout can't be negative");
1221 
1222         getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout);
1223     }
1224 
1225     /**
1226      * Returns setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
1227      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
1228      *
1229      * @return the setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}
1230      * @throws    SocketException if there is an error
1231      * in the underlying protocol, such as a TCP error.
1232      *
1233      * @since   1.1
1234      * @see #setSoTimeout(int)
1235      */
1236     public synchronized int getSoTimeout() throws SocketException {
1237         if (isClosed())
1238             throw new SocketException("Socket is closed");
1239         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
1240         /* extra type safety */
1241         if (o instanceof Integer) {
1242             return ((Integer) o).intValue();
1243         } else {
1244             return 0;
1245         }
1246     }
1247 
1248     /**
1249      * Sets the {@link SocketOptions#SO_SNDBUF SO_SNDBUF} option to the
1250      * specified value for this {@code Socket}.
1251      * The {@link SocketOptions#SO_SNDBUF SO_SNDBUF} option is used by the
1252      * platform's networking code as a hint for the size to set the underlying
1253      * network I/O buffers.
1254      *
1255      * <p>Because {@link SocketOptions#SO_SNDBUF SO_SNDBUF} is a hint,
1256      * applications that want to verify what size the buffers were set to
1257      * should call {@link #getSendBufferSize()}.
1258      *
1259      * @throws    SocketException if there is an error
1260      * in the underlying protocol, such as a TCP error.
1261      *
1262      * @param size the size to which to set the send buffer
1263      * size. This value must be greater than 0.
1264      *
1265      * @throws    IllegalArgumentException if the
1266      * value is 0 or is negative.
1267      *
1268      * @see #getSendBufferSize()
1269      * @since 1.2
1270      */
1271     public synchronized void setSendBufferSize(int size)
1272     throws SocketException{
1273         if (!(size > 0)) {
1274             throw new IllegalArgumentException("negative send size");
1275         }
1276         if (isClosed())
1277             throw new SocketException("Socket is closed");
1278         getImpl().setOption(SocketOptions.SO_SNDBUF, size);
1279     }
1280 
1281     /**
1282      * Get value of the {@link SocketOptions#SO_SNDBUF SO_SNDBUF} option
1283      * for this {@code Socket}, that is the buffer size used by the platform
1284      * for output on this {@code Socket}.
1285      * @return the value of the {@link SocketOptions#SO_SNDBUF SO_SNDBUF}
1286      *         option for this {@code Socket}.
1287      *
1288      * @throws    SocketException if there is an error
1289      * in the underlying protocol, such as a TCP error.
1290      *
1291      * @see #setSendBufferSize(int)
1292      * @since 1.2
1293      */
1294     public synchronized int getSendBufferSize() throws SocketException {
1295         if (isClosed())
1296             throw new SocketException("Socket is closed");
1297         int result = 0;
1298         Object o = getImpl().getOption(SocketOptions.SO_SNDBUF);
1299         if (o instanceof Integer) {
1300             result = ((Integer)o).intValue();
1301         }
1302         return result;
1303     }
1304 
1305     /**
1306      * Sets the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option to the
1307      * specified value for this {@code Socket}. The
1308      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option is
1309      * used by the platform's networking code as a hint for the size to set
1310      * the underlying network I/O buffers.
1311      *
1312      * <p>Increasing the receive buffer size can increase the performance of
1313      * network I/O for high-volume connection, while decreasing it can
1314      * help reduce the backlog of incoming data.
1315      *
1316      * <p>Because {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is a hint,
1317      * applications that want to verify what size the buffers were set to
1318      * should call {@link #getReceiveBufferSize()}.
1319      *
1320      * <p>The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is also used
1321      * to set the TCP receive window that is advertised to the remote peer.
1322      * Generally, the window size can be modified at any time when a socket is
1323      * connected. However, if a receive window larger than 64K is required then
1324      * this must be requested <B>before</B> the socket is connected to the
1325      * remote peer. There are two cases to be aware of:
1326      * <ol>
1327      * <li>For sockets accepted from a ServerSocket, this must be done by calling
1328      * {@link ServerSocket#setReceiveBufferSize(int)} before the ServerSocket
1329      * is bound to a local address.</li>
1330      * <li>For client sockets, setReceiveBufferSize() must be called before
1331      * connecting the socket to its remote peer.</li></ol>
1332      * @param size the size to which to set the receive buffer
1333      * size. This value must be greater than 0.
1334      *
1335      * @throws    IllegalArgumentException if the value is 0 or is
1336      * negative.
1337      *
1338      * @throws    SocketException if there is an error
1339      * in the underlying protocol, such as a TCP error.
1340      *
1341      * @see #getReceiveBufferSize()
1342      * @see ServerSocket#setReceiveBufferSize(int)
1343      * @since 1.2
1344      */
1345     public synchronized void setReceiveBufferSize(int size)
1346     throws SocketException{
1347         if (size <= 0) {
1348             throw new IllegalArgumentException("invalid receive size");
1349         }
1350         if (isClosed())
1351             throw new SocketException("Socket is closed");
1352         getImpl().setOption(SocketOptions.SO_RCVBUF, size);
1353     }
1354 
1355     /**
1356      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
1357      * for this {@code Socket}, that is the buffer size used by the platform
1358      * for input on this {@code Socket}.
1359      *
1360      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
1361      *         option for this {@code Socket}.
1362      * @throws    SocketException if there is an error
1363      * in the underlying protocol, such as a TCP error.
1364      * @see #setReceiveBufferSize(int)
1365      * @since 1.2
1366      */
1367     public synchronized int getReceiveBufferSize()
1368     throws SocketException{
1369         if (isClosed())
1370             throw new SocketException("Socket is closed");
1371         int result = 0;
1372         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
1373         if (o instanceof Integer) {
1374             result = ((Integer)o).intValue();
1375         }
1376         return result;
1377     }
1378 
1379     /**
1380      * Enable/disable {@link SocketOptions#SO_KEEPALIVE SO_KEEPALIVE}.
1381      *
1382      * @param on  whether or not to have socket keep alive turned on.
1383      * @throws    SocketException if there is an error
1384      * in the underlying protocol, such as a TCP error.
1385      * @since 1.3
1386      * @see #getKeepAlive()
1387      */
1388     public void setKeepAlive(boolean on) throws SocketException {
1389         if (isClosed())
1390             throw new SocketException("Socket is closed");
1391         getImpl().setOption(SocketOptions.SO_KEEPALIVE, Boolean.valueOf(on));
1392     }
1393 
1394     /**
1395      * Tests if {@link SocketOptions#SO_KEEPALIVE SO_KEEPALIVE} is enabled.
1396      *
1397      * @return a {@code boolean} indicating whether or not
1398      *         {@link SocketOptions#SO_KEEPALIVE SO_KEEPALIVE} is enabled.
1399      * @throws    SocketException if there is an error
1400      * in the underlying protocol, such as a TCP error.
1401      * @since   1.3
1402      * @see #setKeepAlive(boolean)
1403      */
1404     public boolean getKeepAlive() throws SocketException {
1405         if (isClosed())
1406             throw new SocketException("Socket is closed");
1407         return ((Boolean) getImpl().getOption(SocketOptions.SO_KEEPALIVE)).booleanValue();
1408     }
1409 
1410     /**
1411      * Sets traffic class or type-of-service octet in the IP
1412      * header for packets sent from this Socket.
1413      * As the underlying network implementation may ignore this
1414      * value applications should consider it a hint.
1415      *
1416      * <P> The tc <B>must</B> be in the range {@code 0 <= tc <=
1417      * 255} or an IllegalArgumentException will be thrown.
1418      * <p>Notes:
1419      * <p>For Internet Protocol v4 the value consists of an
1420      * {@code integer}, the least significant 8 bits of which
1421      * represent the value of the TOS octet in IP packets sent by
1422      * the socket.
1423      * RFC 1349 defines the TOS values as follows:
1424      *
1425      * <UL>
1426      * <LI><CODE>IPTOS_LOWCOST (0x02)</CODE></LI>
1427      * <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE></LI>
1428      * <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE></LI>
1429      * <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE></LI>
1430      * </UL>
1431      * The last low order bit is always ignored as this
1432      * corresponds to the MBZ (must be zero) bit.
1433      * <p>
1434      * Setting bits in the precedence field may result in a
1435      * SocketException indicating that the operation is not
1436      * permitted.
1437      * <p>
1438      * As RFC 1122 section 4.2.4.2 indicates, a compliant TCP
1439      * implementation should, but is not required to, let application
1440      * change the TOS field during the lifetime of a connection.
1441      * So whether the type-of-service field can be changed after the
1442      * TCP connection has been established depends on the implementation
1443      * in the underlying platform. Applications should not assume that
1444      * they can change the TOS field after the connection.
1445      * <p>
1446      * For Internet Protocol v6 {@code tc} is the value that
1447      * would be placed into the sin6_flowinfo field of the IP header.
1448      *
1449      * @param tc        an {@code int} value for the bitset.
1450      * @throws SocketException if there is an error setting the
1451      * traffic class or type-of-service
1452      * @since 1.4
1453      * @see #getTrafficClass
1454      * @see SocketOptions#IP_TOS
1455      */
1456     public void setTrafficClass(int tc) throws SocketException {
1457         if (tc < 0 || tc > 255)
1458             throw new IllegalArgumentException("tc is not in range 0 -- 255");
1459 
1460         if (isClosed())
1461             throw new SocketException("Socket is closed");
1462         try {
1463             getImpl().setOption(SocketOptions.IP_TOS, tc);
1464         } catch (SocketException se) {
1465             // not supported if socket already connected
1466             // Solaris returns error in such cases
1467             if(!isConnected())
1468                 throw se;
1469         }
1470     }
1471 
1472     /**
1473      * Gets traffic class or type-of-service in the IP header
1474      * for packets sent from this Socket
1475      * <p>
1476      * As the underlying network implementation may ignore the
1477      * traffic class or type-of-service set using {@link #setTrafficClass(int)}
1478      * this method may return a different value than was previously
1479      * set using the {@link #setTrafficClass(int)} method on this Socket.
1480      *
1481      * @return the traffic class or type-of-service already set
1482      * @throws SocketException if there is an error obtaining the
1483      * traffic class or type-of-service value.
1484      * @since 1.4
1485      * @see #setTrafficClass(int)
1486      * @see SocketOptions#IP_TOS
1487      */
1488     public int getTrafficClass() throws SocketException {
1489         return ((Integer) (getImpl().getOption(SocketOptions.IP_TOS))).intValue();
1490     }
1491 
1492     /**
1493      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
1494      * socket option.
1495      * <p>
1496      * When a TCP connection is closed the connection may remain
1497      * in a timeout state for a period of time after the connection
1498      * is closed (typically known as the {@code TIME_WAIT} state
1499      * or {@code 2MSL} wait state).
1500      * For applications using a well known socket address or port
1501      * it may not be possible to bind a socket to the required
1502      * {@code SocketAddress} if there is a connection in the
1503      * timeout state involving the socket address or port.
1504      * <p>
1505      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
1506      * prior to binding the socket using {@link #bind(SocketAddress)} allows
1507      * the socket to be bound even though a previous connection is in a timeout
1508      * state.
1509      * <p>
1510      * When a {@code Socket} is created the initial setting
1511      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is disabled.
1512      * <p>
1513      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
1514      * enabled or disabled after a socket is bound (See {@link #isBound()})
1515      * is not defined.
1516      *
1517      * @param on  whether to enable or disable the socket option
1518      * @throws    SocketException if an error occurs enabling or
1519      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
1520      *            socket option, or the socket is closed.
1521      * @since 1.4
1522      * @see #getReuseAddress()
1523      * @see #bind(SocketAddress)
1524      * @see #isClosed()
1525      * @see #isBound()
1526      */
1527     public void setReuseAddress(boolean on) throws SocketException {
1528         if (isClosed())
1529             throw new SocketException("Socket is closed");
1530         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
1531     }
1532 
1533     /**
1534      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
1535      *
1536      * @return a {@code boolean} indicating whether or not
1537      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
1538      * @throws    SocketException if there is an error
1539      * in the underlying protocol, such as a TCP error.
1540      * @since   1.4
1541      * @see #setReuseAddress(boolean)
1542      */
1543     public boolean getReuseAddress() throws SocketException {
1544         if (isClosed())
1545             throw new SocketException("Socket is closed");
1546         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
1547     }
1548 
1549     /**
1550      * Closes this socket.
1551      * <p>
1552      * Any thread currently blocked in an I/O operation upon this socket
1553      * will throw a {@link SocketException}.
1554      * <p>
1555      * Once a socket has been closed, it is not available for further networking
1556      * use (i.e. can't be reconnected or rebound). A new socket needs to be
1557      * created.
1558      *
1559      * <p> Closing this socket will also close the socket's
1560      * {@link java.io.InputStream InputStream} and
1561      * {@link java.io.OutputStream OutputStream}.
1562      *
1563      * <p> If this socket has an associated channel then the channel is closed
1564      * as well.
1565      *
1566      * @throws     IOException  if an I/O error occurs when closing this socket.
1567      * @revised 1.4
1568      * @see #isClosed
1569      */
1570     public synchronized void close() throws IOException {
1571         synchronized(closeLock) {
1572             if (isClosed())
1573                 return;
1574             if (created)
1575                 impl.close();
1576             closed = true;
1577         }
1578     }
1579 
1580     /**
1581      * Places the input stream for this socket at "end of stream".
1582      * Any data sent to the input stream side of the socket is acknowledged
1583      * and then silently discarded.
1584      * <p>
1585      * If you read from a socket input stream after invoking this method on the
1586      * socket, the stream's {@code available} method will return 0, and its
1587      * {@code read} methods will return {@code -1} (end of stream).
1588      *
1589      * @throws    IOException if an I/O error occurs when shutting down this
1590      * socket.
1591      *
1592      * @since 1.3
1593      * @see java.net.Socket#shutdownOutput()
1594      * @see java.net.Socket#close()
1595      * @see java.net.Socket#setSoLinger(boolean, int)
1596      * @see #isInputShutdown
1597      */
1598     public void shutdownInput() throws IOException
1599     {
1600         if (isClosed())
1601             throw new SocketException("Socket is closed");
1602         if (!isConnected())
1603             throw new SocketException("Socket is not connected");
1604         if (isInputShutdown())
1605             throw new SocketException("Socket input is already shutdown");
1606         getImpl().shutdownInput();
1607         shutIn = true;
1608     }
1609 
1610     /**
1611      * Disables the output stream for this socket.
1612      * For a TCP socket, any previously written data will be sent
1613      * followed by TCP's normal connection termination sequence.
1614      *
1615      * If you write to a socket output stream after invoking
1616      * shutdownOutput() on the socket, the stream will throw
1617      * an IOException.
1618      *
1619      * @throws    IOException if an I/O error occurs when shutting down this
1620      * socket.
1621      *
1622      * @since 1.3
1623      * @see java.net.Socket#shutdownInput()
1624      * @see java.net.Socket#close()
1625      * @see java.net.Socket#setSoLinger(boolean, int)
1626      * @see #isOutputShutdown
1627      */
1628     public void shutdownOutput() throws IOException
1629     {
1630         if (isClosed())
1631             throw new SocketException("Socket is closed");
1632         if (!isConnected())
1633             throw new SocketException("Socket is not connected");
1634         if (isOutputShutdown())
1635             throw new SocketException("Socket output is already shutdown");
1636         getImpl().shutdownOutput();
1637         shutOut = true;
1638     }
1639 
1640     /**
1641      * Converts this socket to a {@code String}.
1642      *
1643      * @return  a string representation of this socket.
1644      */
1645     public String toString() {
1646         try {
1647             if (isConnected())
1648                 return "Socket[addr=" + getImpl().getInetAddress() +
1649                     ",port=" + getImpl().getPort() +
1650                     ",localport=" + getImpl().getLocalPort() + "]";
1651         } catch (SocketException e) {
1652         }
1653         return "Socket[unconnected]";
1654     }
1655 
1656     /**
1657      * Returns the connection state of the socket.
1658      * <p>
1659      * Note: Closing a socket doesn't clear its connection state, which means
1660      * this method will return {@code true} for a closed socket
1661      * (see {@link #isClosed()}) if it was successfully connected prior
1662      * to being closed.
1663      *
1664      * @return true if the socket was successfully connected to a server
1665      * @since 1.4
1666      */
1667     public boolean isConnected() {
1668         return connected;
1669     }
1670 
1671     /**
1672      * Returns the binding state of the socket.
1673      * <p>
1674      * Note: Closing a socket doesn't clear its binding state, which means
1675      * this method will return {@code true} for a closed socket
1676      * (see {@link #isClosed()}) if it was successfully bound prior
1677      * to being closed.
1678      *
1679      * @return true if the socket was successfully bound to an address
1680      * @since 1.4
1681      * @see #bind
1682      */
1683     public boolean isBound() {
1684         return bound;
1685     }
1686 
1687     /**
1688      * Returns the closed state of the socket.
1689      *
1690      * @return true if the socket has been closed
1691      * @since 1.4
1692      * @see #close
1693      */
1694     public boolean isClosed() {
1695         synchronized(closeLock) {
1696             return closed;
1697         }
1698     }
1699 
1700     /**
1701      * Returns whether the read-half of the socket connection is closed.
1702      *
1703      * @return true if the input of the socket has been shutdown
1704      * @since 1.4
1705      * @see #shutdownInput
1706      */
1707     public boolean isInputShutdown() {
1708         return shutIn;
1709     }
1710 
1711     /**
1712      * Returns whether the write-half of the socket connection is closed.
1713      *
1714      * @return true if the output of the socket has been shutdown
1715      * @since 1.4
1716      * @see #shutdownOutput
1717      */
1718     public boolean isOutputShutdown() {
1719         return shutOut;
1720     }
1721 
1722     /**
1723      * The factory for all client sockets.
1724      */
1725     private static volatile SocketImplFactory factory;
1726 
1727     static SocketImplFactory socketImplFactory() {
1728         return factory;
1729     }
1730 
1731     /**
1732      * Sets the client socket implementation factory for the
1733      * application. The factory can be specified only once.
1734      * <p>
1735      * When an application creates a new client socket, the socket
1736      * implementation factory's {@code createSocketImpl} method is
1737      * called to create the actual socket implementation.
1738      * <p>
1739      * Passing {@code null} to the method is a no-op unless the factory
1740      * was already set.
1741      * <p>If there is a security manager, this method first calls
1742      * the security manager's {@code checkSetFactory} method
1743      * to ensure the operation is allowed.
1744      * This could result in a SecurityException.
1745      *
1746      * @param      fac   the desired factory.
1747      * @throws     IOException  if an I/O error occurs when setting the
1748      *               socket factory.
1749      * @throws     SocketException  if the factory is already defined.
1750      * @throws     SecurityException  if a security manager exists and its
1751      *             {@code checkSetFactory} method doesn't allow the operation.
1752      * @see        java.net.SocketImplFactory#createSocketImpl()
1753      * @see        SecurityManager#checkSetFactory
1754      * @deprecated Use a {@link javax.net.SocketFactory} and subclass {@code Socket}
1755      *    directly.
1756      *    <br> This method provided a way in early JDK releases to replace the
1757      *    system wide implementation of {@code Socket}. It has been mostly
1758      *    obsolete since Java 1.4. If required, a {@code Socket} can be
1759      *    created to use a custom implementation by extending {@code Socket}
1760      *    and using the {@linkplain #Socket(SocketImpl) protected
1761      *    constructor} that takes an {@linkplain SocketImpl implementation}
1762      *    as a parameter.
1763      */
1764     @Deprecated(since = "17")
1765     public static synchronized void setSocketImplFactory(SocketImplFactory fac)
1766         throws IOException
1767     {
1768         if (factory != null) {
1769             throw new SocketException("factory already defined");
1770         }
1771         @SuppressWarnings("removal")
1772         SecurityManager security = System.getSecurityManager();
1773         if (security != null) {
1774             security.checkSetFactory();
1775         }
1776         factory = fac;
1777     }
1778 
1779     /**
1780      * Sets performance preferences for this socket.
1781      *
1782      * <p> Sockets use the TCP/IP protocol by default.  Some implementations
1783      * may offer alternative protocols which have different performance
1784      * characteristics than TCP/IP.  This method allows the application to
1785      * express its own preferences as to how these tradeoffs should be made
1786      * when the implementation chooses from the available protocols.
1787      *
1788      * <p> Performance preferences are described by three integers
1789      * whose values indicate the relative importance of short connection time,
1790      * low latency, and high bandwidth.  The absolute values of the integers
1791      * are irrelevant; in order to choose a protocol the values are simply
1792      * compared, with larger values indicating stronger preferences. Negative
1793      * values represent a lower priority than positive values. If the
1794      * application prefers short connection time over both low latency and high
1795      * bandwidth, for example, then it could invoke this method with the values
1796      * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
1797      * latency, and low latency above short connection time, then it could
1798      * invoke this method with the values {@code (0, 1, 2)}.
1799      *
1800      * <p> Invoking this method after this socket has been connected
1801      * will have no effect.
1802      *
1803      * @param  connectionTime
1804      *         An {@code int} expressing the relative importance of a short
1805      *         connection time
1806      *
1807      * @param  latency
1808      *         An {@code int} expressing the relative importance of low
1809      *         latency
1810      *
1811      * @param  bandwidth
1812      *         An {@code int} expressing the relative importance of high
1813      *         bandwidth
1814      *
1815      * @since 1.5
1816      */
1817     public void setPerformancePreferences(int connectionTime,
1818                                           int latency,
1819                                           int bandwidth)
1820     {
1821         /* Not implemented yet */
1822     }
1823 
1824 
1825     /**
1826      * Sets the value of a socket option.
1827      *
1828      * @param <T> The type of the socket option value
1829      * @param name The socket option
1830      * @param value The value of the socket option. A value of {@code null}
1831      *              may be valid for some options.
1832      * @return this Socket
1833      *
1834      * @throws UnsupportedOperationException if the socket does not support
1835      *         the option.
1836      *
1837      * @throws IllegalArgumentException if the value is not valid for
1838      *         the option.
1839      *
1840      * @throws IOException if an I/O error occurs, or if the socket is closed.
1841      *
1842      * @throws NullPointerException if name is {@code null}
1843      *
1844      * @throws SecurityException if a security manager is set and if the socket
1845      *         option requires a security permission and if the caller does
1846      *         not have the required permission.
1847      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1848      *         do not require any security permission.
1849      *
1850      * @since 9
1851      */
1852     public <T> Socket setOption(SocketOption<T> name, T value) throws IOException {
1853         Objects.requireNonNull(name);
1854         if (isClosed())
1855             throw new SocketException("Socket is closed");
1856         getImpl().setOption(name, value);
1857         return this;
1858     }
1859 
1860     /**
1861      * Returns the value of a socket option.
1862      *
1863      * @param <T> The type of the socket option value
1864      * @param name The socket option
1865      *
1866      * @return The value of the socket option.
1867      *
1868      * @throws UnsupportedOperationException if the socket does not support
1869      *         the option.
1870      *
1871      * @throws IOException if an I/O error occurs, or if the socket is closed.
1872      *
1873      * @throws NullPointerException if name is {@code null}
1874      *
1875      * @throws SecurityException if a security manager is set and if the socket
1876      *         option requires a security permission and if the caller does
1877      *         not have the required permission.
1878      *         {@link java.net.StandardSocketOptions StandardSocketOptions}
1879      *         do not require any security permission.
1880      *
1881      * @since 9
1882      */
1883     @SuppressWarnings("unchecked")
1884     public <T> T getOption(SocketOption<T> name) throws IOException {
1885         Objects.requireNonNull(name);
1886         if (isClosed())
1887             throw new SocketException("Socket is closed");
1888         return getImpl().getOption(name);
1889     }
1890 
1891     // cache of unmodifiable impl options. Possibly set racy, in impl we trust
1892     private volatile Set<SocketOption<?>> options;
1893 
1894     /**
1895      * Returns a set of the socket options supported by this socket.
1896      *
1897      * This method will continue to return the set of options even after
1898      * the socket has been closed.
1899      *
1900      * @return A set of the socket options supported by this socket. This set
1901      *         may be empty if the socket's SocketImpl cannot be created.
1902      *
1903      * @since 9
1904      */
1905     public Set<SocketOption<?>> supportedOptions() {
1906         Set<SocketOption<?>> so = options;
1907         if (so != null)
1908             return so;
1909 
1910         try {
1911             SocketImpl impl = getImpl();
1912             options = Collections.unmodifiableSet(impl.supportedOptions());
1913         } catch (IOException e) {
1914             options = Collections.emptySet();
1915         }
1916         return options;
1917     }
1918 }