1 /*
   2  * Copyright (c) 1995, 2013, 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.FileDescriptor;
  29 import java.io.IOException;
  30 import java.nio.channels.ServerSocketChannel;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedExceptionAction;
  33 
  34 /**
  35  * This class implements server sockets. A server socket waits for
  36  * requests to come in over the network. It performs some operation
  37  * based on that request, and then possibly returns a result to the requester.
  38  * <p>
  39  * The actual work of the server socket is performed by an instance
  40  * of the {@code SocketImpl} class. An application can
  41  * change the socket factory that creates the socket
  42  * implementation to configure itself to create sockets
  43  * appropriate to the local firewall.
  44  *
  45  * @author  unascribed
  46  * @see     java.net.SocketImpl
  47  * @see     java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
  48  * @see     java.nio.channels.ServerSocketChannel
  49  * @since   JDK1.0
  50  */
  51 public
  52 class ServerSocket implements java.io.Closeable {
  53     /**
  54      * Various states of this socket.
  55      */
  56     private boolean created = false;
  57     private boolean bound = false;
  58     private boolean closed = false;
  59     private Object closeLock = new Object();
  60 
  61     /**
  62      * The implementation of this Socket.
  63      */
  64     private SocketImpl impl;
  65 
  66     /**
  67      * Are we using an older SocketImpl?
  68      */
  69     private boolean oldImpl = false;
  70 
  71     /**
  72      * Package-private constructor to create a ServerSocket associated with
  73      * the given SocketImpl.
  74      */
  75     ServerSocket(SocketImpl impl) {
  76         this.impl = impl;
  77         impl.setServerSocket(this);
  78     }
  79 
  80     /**
  81      * Creates an unbound server socket.
  82      *
  83      * @exception IOException IO error when opening the socket.
  84      * @revised 1.4
  85      */
  86     public ServerSocket() throws IOException {
  87         setImpl();
  88     }
  89 
  90     /**
  91      * Creates a server socket, bound to the specified port. A port number
  92      * of {@code 0} means that the port number is automatically
  93      * allocated, typically from an ephemeral port range. This port
  94      * number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
  95      * <p>
  96      * The maximum queue length for incoming connection indications (a
  97      * request to connect) is set to {@code 50}. If a connection
  98      * indication arrives when the queue is full, the connection is refused.
  99      * <p>
 100      * If the application has specified a server socket factory, that
 101      * factory's {@code createSocketImpl} method is called to create
 102      * the actual socket implementation. Otherwise a "plain" socket is created.
 103      * <p>
 104      * If there is a security manager,
 105      * its {@code checkListen} method is called
 106      * with the {@code port} argument
 107      * as its argument to ensure the operation is allowed.
 108      * This could result in a SecurityException.
 109      *
 110      *
 111      * @param      port  the port number, or {@code 0} to use a port
 112      *                   number that is automatically allocated.
 113      *
 114      * @exception  IOException  if an I/O error occurs when opening the socket.
 115      * @exception  SecurityException
 116      * if a security manager exists and its {@code checkListen}
 117      * method doesn't allow the operation.
 118      * @exception  IllegalArgumentException if the port parameter is outside
 119      *             the specified range of valid port values, which is between
 120      *             0 and 65535, inclusive.
 121      *
 122      * @see        java.net.SocketImpl
 123      * @see        java.net.SocketImplFactory#createSocketImpl()
 124      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
 125      * @see        SecurityManager#checkListen
 126      */
 127     public ServerSocket(int port) throws IOException {
 128         this(port, 50, null);
 129     }
 130 
 131     /**
 132      * Creates a server socket and binds it to the specified local port
 133      * number, with the specified backlog.
 134      * A port number of {@code 0} means that the port number is
 135      * automatically allocated, typically from an ephemeral port range.
 136      * This port number can then be retrieved by calling
 137      * {@link #getLocalPort getLocalPort}.
 138      * <p>
 139      * The maximum queue length for incoming connection indications (a
 140      * request to connect) is set to the {@code backlog} parameter. If
 141      * a connection indication arrives when the queue is full, the
 142      * connection is refused.
 143      * <p>
 144      * If the application has specified a server socket factory, that
 145      * factory's {@code createSocketImpl} method is called to create
 146      * the actual socket implementation. Otherwise a "plain" socket is created.
 147      * <p>
 148      * If there is a security manager,
 149      * its {@code checkListen} method is called
 150      * with the {@code port} argument
 151      * as its argument to ensure the operation is allowed.
 152      * This could result in a SecurityException.
 153      *
 154      * The {@code backlog} argument is the requested maximum number of
 155      * pending connections on the socket. Its exact semantics are implementation
 156      * specific. In particular, an implementation may impose a maximum length
 157      * or may choose to ignore the parameter altogther. The value provided
 158      * should be greater than {@code 0}. If it is less than or equal to
 159      * {@code 0}, then an implementation specific default will be used.
 160      *
 161      * @param      port     the port number, or {@code 0} to use a port
 162      *                      number that is automatically allocated.
 163      * @param      backlog  requested maximum length of the queue of incoming
 164      *                      connections.
 165      *
 166      * @exception  IOException  if an I/O error occurs when opening the socket.
 167      * @exception  SecurityException
 168      * if a security manager exists and its {@code checkListen}
 169      * method doesn't allow the operation.
 170      * @exception  IllegalArgumentException if the port parameter is outside
 171      *             the specified range of valid port values, which is between
 172      *             0 and 65535, inclusive.
 173      *
 174      * @see        java.net.SocketImpl
 175      * @see        java.net.SocketImplFactory#createSocketImpl()
 176      * @see        java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
 177      * @see        SecurityManager#checkListen
 178      */
 179     public ServerSocket(int port, int backlog) throws IOException {
 180         this(port, backlog, null);
 181     }
 182 
 183     /**
 184      * Create a server with the specified port, listen backlog, and
 185      * local IP address to bind to.  The <i>bindAddr</i> argument
 186      * can be used on a multi-homed host for a ServerSocket that
 187      * will only accept connect requests to one of its addresses.
 188      * If <i>bindAddr</i> is null, it will default accepting
 189      * connections on any/all local addresses.
 190      * The port must be between 0 and 65535, inclusive.
 191      * A port number of {@code 0} means that the port number is
 192      * automatically allocated, typically from an ephemeral port range.
 193      * This port number can then be retrieved by calling
 194      * {@link #getLocalPort getLocalPort}.
 195      *
 196      * <P>If there is a security manager, this method
 197      * calls its {@code checkListen} method
 198      * with the {@code port} argument
 199      * as its argument to ensure the operation is allowed.
 200      * This could result in a SecurityException.
 201      *
 202      * The {@code backlog} argument is the requested maximum number of
 203      * pending connections on the socket. Its exact semantics are implementation
 204      * specific. In particular, an implementation may impose a maximum length
 205      * or may choose to ignore the parameter altogther. The value provided
 206      * should be greater than {@code 0}. If it is less than or equal to
 207      * {@code 0}, then an implementation specific default will be used.
 208      *
 209      * @param port  the port number, or {@code 0} to use a port
 210      *              number that is automatically allocated.
 211      * @param backlog requested maximum length of the queue of incoming
 212      *                connections.
 213      * @param bindAddr the local InetAddress the server will bind to
 214      *
 215      * @throws  SecurityException if a security manager exists and
 216      * its {@code checkListen} method doesn't allow the operation.
 217      *
 218      * @throws  IOException if an I/O error occurs when opening the socket.
 219      * @exception  IllegalArgumentException if the port parameter is outside
 220      *             the specified range of valid port values, which is between
 221      *             0 and 65535, inclusive.
 222      *
 223      * @see SocketOptions
 224      * @see SocketImpl
 225      * @see SecurityManager#checkListen
 226      * @since   JDK1.1
 227      */
 228     public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
 229         setImpl();
 230         if (port < 0 || port > 0xFFFF)
 231             throw new IllegalArgumentException(
 232                        "Port value out of range: " + port);
 233         if (backlog < 1)
 234           backlog = 50;
 235         try {
 236             bind(new InetSocketAddress(bindAddr, port), backlog);
 237         } catch(SecurityException e) {
 238             close();
 239             throw e;
 240         } catch(IOException e) {
 241             close();
 242             throw e;
 243         }
 244     }
 245 
 246     /**
 247      * Get the {@code SocketImpl} attached to this socket, creating
 248      * it if necessary.
 249      *
 250      * @return  the {@code SocketImpl} attached to that ServerSocket.
 251      * @throws SocketException if creation fails.
 252      * @since 1.4
 253      */
 254     SocketImpl getImpl() throws SocketException {
 255         if (!created)
 256             createImpl();
 257         return impl;
 258     }
 259 
 260     private void checkOldImpl() {
 261         if (impl == null)
 262             return;
 263         // SocketImpl.connect() is a protected method, therefore we need to use
 264         // getDeclaredMethod, therefore we need permission to access the member
 265         try {
 266             AccessController.doPrivileged(
 267                 new PrivilegedExceptionAction<Void>() {
 268                     public Void run() throws NoSuchMethodException {
 269                         impl.getClass().getDeclaredMethod("connect",
 270                                                           SocketAddress.class,
 271                                                           int.class);
 272                         return null;
 273                     }
 274                 });
 275         } catch (java.security.PrivilegedActionException e) {
 276             oldImpl = true;
 277         }
 278     }
 279 
 280     private void setImpl() {
 281         if (factory != null) {
 282             impl = factory.createSocketImpl();
 283             checkOldImpl();
 284         } else {
 285             // No need to do a checkOldImpl() here, we know it's an up to date
 286             // SocketImpl!
 287             impl = new SocksSocketImpl();
 288         }
 289         if (impl != null)
 290             impl.setServerSocket(this);
 291     }
 292 
 293     /**
 294      * Creates the socket implementation.
 295      *
 296      * @throws IOException if creation fails
 297      * @since 1.4
 298      */
 299     void createImpl() throws SocketException {
 300         if (impl == null)
 301             setImpl();
 302         try {
 303             impl.create(true);
 304             created = true;
 305         } catch (IOException e) {
 306             throw new SocketException(e.getMessage());
 307         }
 308     }
 309 
 310     /**
 311      *
 312      * Binds the {@code ServerSocket} to a specific address
 313      * (IP address and port number).
 314      * <p>
 315      * If the address is {@code null}, then the system will pick up
 316      * an ephemeral port and a valid local address to bind the socket.
 317      *
 318      * @param   endpoint        The IP address and port number to bind to.
 319      * @throws  IOException if the bind operation fails, or if the socket
 320      *                     is already bound.
 321      * @throws  SecurityException       if a {@code SecurityManager} is present and
 322      * its {@code checkListen} method doesn't allow the operation.
 323      * @throws  IllegalArgumentException if endpoint is a
 324      *          SocketAddress subclass not supported by this socket
 325      * @since 1.4
 326      */
 327     public void bind(SocketAddress endpoint) throws IOException {
 328         bind(endpoint, 50);
 329     }
 330 
 331     /**
 332      *
 333      * Binds the {@code ServerSocket} to a specific address
 334      * (IP address and port number).
 335      * <p>
 336      * If the address is {@code null}, then the system will pick up
 337      * an ephemeral port and a valid local address to bind the socket.
 338      * <P>
 339      * The {@code backlog} argument is the requested maximum number of
 340      * pending connections on the socket. Its exact semantics are implementation
 341      * specific. In particular, an implementation may impose a maximum length
 342      * or may choose to ignore the parameter altogther. The value provided
 343      * should be greater than {@code 0}. If it is less than or equal to
 344      * {@code 0}, then an implementation specific default will be used.
 345      * @param   endpoint        The IP address and port number to bind to.
 346      * @param   backlog         requested maximum length of the queue of
 347      *                          incoming connections.
 348      * @throws  IOException if the bind operation fails, or if the socket
 349      *                     is already bound.
 350      * @throws  SecurityException       if a {@code SecurityManager} is present and
 351      * its {@code checkListen} method doesn't allow the operation.
 352      * @throws  IllegalArgumentException if endpoint is a
 353      *          SocketAddress subclass not supported by this socket
 354      * @since 1.4
 355      */
 356     public void bind(SocketAddress endpoint, int backlog) throws IOException {
 357         if (isClosed())
 358             throw new SocketException("Socket is closed");
 359         if (!oldImpl && isBound())
 360             throw new SocketException("Already bound");
 361         if (endpoint == null)
 362             endpoint = new InetSocketAddress(0);
 363         if (!(endpoint instanceof InetSocketAddress))
 364             throw new IllegalArgumentException("Unsupported address type");
 365         InetSocketAddress epoint = (InetSocketAddress) endpoint;
 366         if (epoint.isUnresolved())
 367             throw new SocketException("Unresolved address");
 368         if (backlog < 1)
 369           backlog = 50;
 370         try {
 371             SecurityManager security = System.getSecurityManager();
 372             if (security != null)
 373                 security.checkListen(epoint.getPort());
 374             getImpl().bind(epoint.getAddress(), epoint.getPort());
 375             getImpl().listen(backlog);
 376             bound = true;
 377         } catch(SecurityException e) {
 378             bound = false;
 379             throw e;
 380         } catch(IOException e) {
 381             bound = false;
 382             throw e;
 383         }
 384     }
 385 
 386     /**
 387      * Returns the local address of this server socket.
 388      * <p>
 389      * If the socket was bound prior to being {@link #close closed},
 390      * then this method will continue to return the local address
 391      * after the socket is closed.
 392      * <p>
 393      * If there is a security manager set, its {@code checkConnect} method is
 394      * called with the local address and {@code -1} as its arguments to see
 395      * if the operation is allowed. If the operation is not allowed,
 396      * the {@link InetAddress#getLoopbackAddress loopback} address is returned.
 397      *
 398      * @return  the address to which this socket is bound,
 399      *          or the loopback address if denied by the security manager,
 400      *          or {@code null} if the socket is unbound.
 401      *
 402      * @see SecurityManager#checkConnect
 403      */
 404     public InetAddress getInetAddress() {
 405         if (!isBound())
 406             return null;
 407         try {
 408             InetAddress in = getImpl().getInetAddress();
 409             SecurityManager sm = System.getSecurityManager();
 410             if (sm != null)
 411                 sm.checkConnect(in.getHostAddress(), -1);
 412             return in;
 413         } catch (SecurityException e) {
 414             return InetAddress.getLoopbackAddress();
 415         } catch (SocketException e) {
 416             // nothing
 417             // If we're bound, the impl has been created
 418             // so we shouldn't get here
 419         }
 420         return null;
 421     }
 422 
 423     /**
 424      * Returns the port number on which this socket is listening.
 425      * <p>
 426      * If the socket was bound prior to being {@link #close closed},
 427      * then this method will continue to return the port number
 428      * after the socket is closed.
 429      *
 430      * @return  the port number to which this socket is listening or
 431      *          -1 if the socket is not bound yet.
 432      */
 433     public int getLocalPort() {
 434         if (!isBound())
 435             return -1;
 436         try {
 437             return getImpl().getLocalPort();
 438         } catch (SocketException e) {
 439             // nothing
 440             // If we're bound, the impl has been created
 441             // so we shouldn't get here
 442         }
 443         return -1;
 444     }
 445 
 446     /**
 447      * Returns the address of the endpoint this socket is bound to.
 448      * <p>
 449      * If the socket was bound prior to being {@link #close closed},
 450      * then this method will continue to return the address of the endpoint
 451      * after the socket is closed.
 452      * <p>
 453      * If there is a security manager set, its {@code checkConnect} method is
 454      * called with the local address and {@code -1} as its arguments to see
 455      * if the operation is allowed. If the operation is not allowed,
 456      * a {@code SocketAddress} representing the
 457      * {@link InetAddress#getLoopbackAddress loopback} address and the local
 458      * port to which the socket is bound is returned.
 459      *
 460      * @return a {@code SocketAddress} representing the local endpoint of
 461      *         this socket, or a {@code SocketAddress} representing the
 462      *         loopback address if denied by the security manager,
 463      *         or {@code null} if the socket is not bound yet.
 464      *
 465      * @see #getInetAddress()
 466      * @see #getLocalPort()
 467      * @see #bind(SocketAddress)
 468      * @see SecurityManager#checkConnect
 469      * @since 1.4
 470      */
 471 
 472     public SocketAddress getLocalSocketAddress() {
 473         if (!isBound())
 474             return null;
 475         return new InetSocketAddress(getInetAddress(), getLocalPort());
 476     }
 477 
 478     /**
 479      * Listens for a connection to be made to this socket and accepts
 480      * it. The method blocks until a connection is made.
 481      *
 482      * <p>A new Socket {@code s} is created and, if there
 483      * is a security manager,
 484      * the security manager's {@code checkAccept} method is called
 485      * with {@code s.getInetAddress().getHostAddress()} and
 486      * {@code s.getPort()}
 487      * as its arguments to ensure the operation is allowed.
 488      * This could result in a SecurityException.
 489      *
 490      * @exception  IOException  if an I/O error occurs when waiting for a
 491      *               connection.
 492      * @exception  SecurityException  if a security manager exists and its
 493      *             {@code checkAccept} method doesn't allow the operation.
 494      * @exception  SocketTimeoutException if a timeout was previously set with setSoTimeout and
 495      *             the timeout has been reached.
 496      * @exception  java.nio.channels.IllegalBlockingModeException
 497      *             if this socket has an associated channel, the channel is in
 498      *             non-blocking mode, and there is no connection ready to be
 499      *             accepted
 500      *
 501      * @return the new Socket
 502      * @see SecurityManager#checkAccept
 503      * @revised 1.4
 504      * @spec JSR-51
 505      */
 506     public Socket accept() throws IOException {
 507         if (isClosed())
 508             throw new SocketException("Socket is closed");
 509         if (!isBound())
 510             throw new SocketException("Socket is not bound yet");
 511         Socket s = new Socket((SocketImpl) null);
 512         implAccept(s);
 513         return s;
 514     }
 515 
 516     /**
 517      * Subclasses of ServerSocket use this method to override accept()
 518      * to return their own subclass of socket.  So a FooServerSocket
 519      * will typically hand this method an <i>empty</i> FooSocket.  On
 520      * return from implAccept the FooSocket will be connected to a client.
 521      *
 522      * @param s the Socket
 523      * @throws java.nio.channels.IllegalBlockingModeException
 524      *         if this socket has an associated channel,
 525      *         and the channel is in non-blocking mode
 526      * @throws IOException if an I/O error occurs when waiting
 527      * for a connection.
 528      * @since   JDK1.1
 529      * @revised 1.4
 530      * @spec JSR-51
 531      */
 532     protected final void implAccept(Socket s) throws IOException {
 533         SocketImpl si = null;
 534         try {
 535             if (s.impl == null)
 536               s.setImpl();
 537             else {
 538                 s.impl.reset();
 539             }
 540             si = s.impl;
 541             s.impl = null;
 542             si.address = new InetAddress();
 543             si.fd = new FileDescriptor();
 544             getImpl().accept(si);
 545 
 546             SecurityManager security = System.getSecurityManager();
 547             if (security != null) {
 548                 security.checkAccept(si.getInetAddress().getHostAddress(),
 549                                      si.getPort());
 550             }
 551         } catch (IOException e) {
 552             if (si != null)
 553                 si.reset();
 554             s.impl = si;
 555             throw e;
 556         } catch (SecurityException e) {
 557             if (si != null)
 558                 si.reset();
 559             s.impl = si;
 560             throw e;
 561         }
 562         s.impl = si;
 563         s.postAccept();
 564     }
 565 
 566     /**
 567      * Closes this socket.
 568      *
 569      * Any thread currently blocked in {@link #accept()} will throw
 570      * a {@link SocketException}.
 571      *
 572      * <p> If this socket has an associated channel then the channel is closed
 573      * as well.
 574      *
 575      * @exception  IOException  if an I/O error occurs when closing the socket.
 576      * @revised 1.4
 577      * @spec JSR-51
 578      */
 579     public void close() throws IOException {
 580         synchronized(closeLock) {
 581             if (isClosed())
 582                 return;
 583             if (created)
 584                 impl.close();
 585             closed = true;
 586         }
 587     }
 588 
 589     /**
 590      * Returns the unique {@link java.nio.channels.ServerSocketChannel} object
 591      * associated with this socket, if any.
 592      *
 593      * <p> A server socket will have a channel if, and only if, the channel
 594      * itself was created via the {@link
 595      * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}
 596      * method.
 597      *
 598      * @return  the server-socket channel associated with this socket,
 599      *          or {@code null} if this socket was not created
 600      *          for a channel
 601      *
 602      * @since 1.4
 603      * @spec JSR-51
 604      */
 605     public ServerSocketChannel getChannel() {
 606         return null;
 607     }
 608 
 609     /**
 610      * Returns the binding state of the ServerSocket.
 611      *
 612      * @return true if the ServerSocket successfully bound to an address
 613      * @since 1.4
 614      */
 615     public boolean isBound() {
 616         // Before 1.3 ServerSockets were always bound during creation
 617         return bound || oldImpl;
 618     }
 619 
 620     /**
 621      * Returns the closed state of the ServerSocket.
 622      *
 623      * @return true if the socket has been closed
 624      * @since 1.4
 625      */
 626     public boolean isClosed() {
 627         synchronized(closeLock) {
 628             return closed;
 629         }
 630     }
 631 
 632     /**
 633      * Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the
 634      * specified timeout, in milliseconds.  With this option set to a non-zero
 635      * timeout, a call to accept() for this ServerSocket
 636      * will block for only this amount of time.  If the timeout expires,
 637      * a <B>java.net.SocketTimeoutException</B> is raised, though the
 638      * ServerSocket is still valid.  The option <B>must</B> be enabled
 639      * prior to entering the blocking operation to have effect.  The
 640      * timeout must be {@code > 0}.
 641      * A timeout of zero is interpreted as an infinite timeout.
 642      * @param timeout the specified timeout, in milliseconds
 643      * @exception SocketException if there is an error in
 644      * the underlying protocol, such as a TCP error.
 645      * @since   JDK1.1
 646      * @see #getSoTimeout()
 647      */
 648     public synchronized void setSoTimeout(int timeout) throws SocketException {
 649         if (isClosed())
 650             throw new SocketException("Socket is closed");
 651         getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
 652     }
 653 
 654     /**
 655      * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
 656      * 0 returns implies that the option is disabled (i.e., timeout of infinity).
 657      * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
 658      * @exception IOException if an I/O error occurs
 659      * @since   JDK1.1
 660      * @see #setSoTimeout(int)
 661      */
 662     public synchronized int getSoTimeout() throws IOException {
 663         if (isClosed())
 664             throw new SocketException("Socket is closed");
 665         Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
 666         /* extra type safety */
 667         if (o instanceof Integer) {
 668             return ((Integer) o).intValue();
 669         } else {
 670             return 0;
 671         }
 672     }
 673 
 674     /**
 675      * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 676      * socket option.
 677      * <p>
 678      * When a TCP connection is closed the connection may remain
 679      * in a timeout state for a period of time after the connection
 680      * is closed (typically known as the {@code TIME_WAIT} state
 681      * or {@code 2MSL} wait state).
 682      * For applications using a well known socket address or port
 683      * it may not be possible to bind a socket to the required
 684      * {@code SocketAddress} if there is a connection in the
 685      * timeout state involving the socket address or port.
 686      * <p>
 687      * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
 688      * binding the socket using {@link #bind(SocketAddress)} allows the socket
 689      * to be bound even though a previous connection is in a timeout state.
 690      * <p>
 691      * When a {@code ServerSocket} is created the initial setting
 692      * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
 693      * Applications can use {@link #getReuseAddress()} to determine the initial
 694      * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
 695      * <p>
 696      * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
 697      * enabled or disabled after a socket is bound (See {@link #isBound()})
 698      * is not defined.
 699      *
 700      * @param on  whether to enable or disable the socket option
 701      * @exception SocketException if an error occurs enabling or
 702      *            disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
 703      *            socket option, or the socket is closed.
 704      * @since 1.4
 705      * @see #getReuseAddress()
 706      * @see #bind(SocketAddress)
 707      * @see #isBound()
 708      * @see #isClosed()
 709      */
 710     public void setReuseAddress(boolean on) throws SocketException {
 711         if (isClosed())
 712             throw new SocketException("Socket is closed");
 713         getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
 714     }
 715 
 716     /**
 717      * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 718      *
 719      * @return a {@code boolean} indicating whether or not
 720      *         {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
 721      * @exception SocketException if there is an error
 722      * in the underlying protocol, such as a TCP error.
 723      * @since   1.4
 724      * @see #setReuseAddress(boolean)
 725      */
 726     public boolean getReuseAddress() throws SocketException {
 727         if (isClosed())
 728             throw new SocketException("Socket is closed");
 729         return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
 730     }
 731 
 732     /**
 733      * Returns the implementation address and implementation port of
 734      * this socket as a {@code String}.
 735      * <p>
 736      * If there is a security manager set, its {@code checkConnect} method is
 737      * called with the local address and {@code -1} as its arguments to see
 738      * if the operation is allowed. If the operation is not allowed,
 739      * an {@code InetAddress} representing the
 740      * {@link InetAddress#getLoopbackAddress loopback} address is returned as
 741      * the implementation address.
 742      *
 743      * @return  a string representation of this socket.
 744      */
 745     public String toString() {
 746         if (!isBound())
 747             return "ServerSocket[unbound]";
 748         InetAddress in;
 749         if (System.getSecurityManager() != null)
 750             in = InetAddress.getLoopbackAddress();
 751         else
 752             in = impl.getInetAddress();
 753         return "ServerSocket[addr=" + in +
 754                 ",localport=" + impl.getLocalPort()  + "]";
 755     }
 756 
 757     void setBound() {
 758         bound = true;
 759     }
 760 
 761     void setCreated() {
 762         created = true;
 763     }
 764 
 765     /**
 766      * The factory for all server sockets.
 767      */
 768     private static SocketImplFactory factory = null;
 769 
 770     /**
 771      * Sets the server socket implementation factory for the
 772      * application. The factory can be specified only once.
 773      * <p>
 774      * When an application creates a new server socket, the socket
 775      * implementation factory's {@code createSocketImpl} method is
 776      * called to create the actual socket implementation.
 777      * <p>
 778      * Passing {@code null} to the method is a no-op unless the factory
 779      * was already set.
 780      * <p>
 781      * If there is a security manager, this method first calls
 782      * the security manager's {@code checkSetFactory} method
 783      * to ensure the operation is allowed.
 784      * This could result in a SecurityException.
 785      *
 786      * @param      fac   the desired factory.
 787      * @exception  IOException  if an I/O error occurs when setting the
 788      *               socket factory.
 789      * @exception  SocketException  if the factory has already been defined.
 790      * @exception  SecurityException  if a security manager exists and its
 791      *             {@code checkSetFactory} method doesn't allow the operation.
 792      * @see        java.net.SocketImplFactory#createSocketImpl()
 793      * @see        SecurityManager#checkSetFactory
 794      */
 795     public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
 796         if (factory != null) {
 797             throw new SocketException("factory already defined");
 798         }
 799         SecurityManager security = System.getSecurityManager();
 800         if (security != null) {
 801             security.checkSetFactory();
 802         }
 803         factory = fac;
 804     }
 805 
 806     /**
 807      * Sets a default proposed value for the
 808      * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
 809      * accepted from this {@code ServerSocket}. The value actually set
 810      * in the accepted socket must be determined by calling
 811      * {@link Socket#getReceiveBufferSize()} after the socket
 812      * is returned by {@link #accept()}.
 813      * <p>
 814      * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
 815      * set the size of the internal socket receive buffer, and to set the size
 816      * of the TCP receive window that is advertized to the remote peer.
 817      * <p>
 818      * It is possible to change the value subsequently, by calling
 819      * {@link Socket#setReceiveBufferSize(int)}. However, if the application
 820      * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
 821      * then the proposed value must be set in the ServerSocket <B>before</B>
 822      * it is bound to a local address. This implies, that the ServerSocket must be
 823      * created with the no-argument constructor, then setReceiveBufferSize() must
 824      * be called and lastly the ServerSocket is bound to an address by calling bind().
 825      * <p>
 826      * Failure to do this will not cause an error, and the buffer size may be set to the
 827      * requested value but the TCP receive window in sockets accepted from
 828      * this ServerSocket will be no larger than 64K bytes.
 829      *
 830      * @exception SocketException if there is an error
 831      * in the underlying protocol, such as a TCP error.
 832      *
 833      * @param size the size to which to set the receive buffer
 834      * size. This value must be greater than 0.
 835      *
 836      * @exception IllegalArgumentException if the
 837      * value is 0 or is negative.
 838      *
 839      * @since 1.4
 840      * @see #getReceiveBufferSize
 841      */
 842      public synchronized void setReceiveBufferSize (int size) throws SocketException {
 843         if (!(size > 0)) {
 844             throw new IllegalArgumentException("negative receive size");
 845         }
 846         if (isClosed())
 847             throw new SocketException("Socket is closed");
 848         getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
 849     }
 850 
 851     /**
 852      * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
 853      * for this {@code ServerSocket}, that is the proposed buffer size that
 854      * will be used for Sockets accepted from this {@code ServerSocket}.
 855      *
 856      * <p>Note, the value actually set in the accepted socket is determined by
 857      * calling {@link Socket#getReceiveBufferSize()}.
 858      * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
 859      *         option for this {@code Socket}.
 860      * @exception SocketException if there is an error
 861      *            in the underlying protocol, such as a TCP error.
 862      * @see #setReceiveBufferSize(int)
 863      * @since 1.4
 864      */
 865     public synchronized int getReceiveBufferSize()
 866     throws SocketException{
 867         if (isClosed())
 868             throw new SocketException("Socket is closed");
 869         int result = 0;
 870         Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
 871         if (o instanceof Integer) {
 872             result = ((Integer)o).intValue();
 873         }
 874         return result;
 875     }
 876 
 877     /**
 878      * Sets performance preferences for this ServerSocket.
 879      *
 880      * <p> Sockets use the TCP/IP protocol by default.  Some implementations
 881      * may offer alternative protocols which have different performance
 882      * characteristics than TCP/IP.  This method allows the application to
 883      * express its own preferences as to how these tradeoffs should be made
 884      * when the implementation chooses from the available protocols.
 885      *
 886      * <p> Performance preferences are described by three integers
 887      * whose values indicate the relative importance of short connection time,
 888      * low latency, and high bandwidth.  The absolute values of the integers
 889      * are irrelevant; in order to choose a protocol the values are simply
 890      * compared, with larger values indicating stronger preferences.  If the
 891      * application prefers short connection time over both low latency and high
 892      * bandwidth, for example, then it could invoke this method with the values
 893      * {@code (1, 0, 0)}.  If the application prefers high bandwidth above low
 894      * latency, and low latency above short connection time, then it could
 895      * invoke this method with the values {@code (0, 1, 2)}.
 896      *
 897      * <p> Invoking this method after this socket has been bound
 898      * will have no effect. This implies that in order to use this capability
 899      * requires the socket to be created with the no-argument constructor.
 900      *
 901      * @param  connectionTime
 902      *         An {@code int} expressing the relative importance of a short
 903      *         connection time
 904      *
 905      * @param  latency
 906      *         An {@code int} expressing the relative importance of low
 907      *         latency
 908      *
 909      * @param  bandwidth
 910      *         An {@code int} expressing the relative importance of high
 911      *         bandwidth
 912      *
 913      * @since 1.5
 914      */
 915     public void setPerformancePreferences(int connectionTime,
 916                                           int latency,
 917                                           int bandwidth)
 918     {
 919         /* Not implemented yet */
 920     }
 921 
 922 }