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