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