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