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