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