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