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