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