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