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.FileDescriptor; 29 import java.io.IOException; 30 import java.lang.reflect.Constructor; 31 import java.lang.reflect.InvocationTargetException; 32 import java.nio.channels.ServerSocketChannel; 33 import java.security.AccessController; 34 import java.security.PrivilegedExceptionAction; 35 import java.util.Objects; 36 import java.util.Set; 37 import java.util.Collections; 38 39 import jdk.internal.access.JavaNetSocketAccess; 40 import jdk.internal.access.SharedSecrets; 41 import sun.net.PlatformSocketImpl; 42 43 /** 44 * This class implements server sockets. A server socket waits for 45 * requests to come in over the network. It performs some operation 46 * based on that request, and then possibly returns a result to the requester. 47 * <p> 48 * The actual work of the server socket is performed by an instance 49 * of the {@code SocketImpl} class. An application can 50 * change the socket factory that creates the socket 51 * implementation to configure itself to create sockets 52 * appropriate to the local firewall. 53 * 54 * @author unascribed 55 * @see java.net.SocketImpl 56 * @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) 57 * @see java.nio.channels.ServerSocketChannel 58 * @since 1.0 59 */ 60 public 61 class ServerSocket implements java.io.Closeable { 62 /** 63 * Various states of this socket. 64 */ 65 private boolean created = false; 66 private boolean bound = false; 67 private boolean closed = false; 68 private Object closeLock = new Object(); 69 70 /** 71 * The implementation of this Socket. 72 */ 73 private SocketImpl impl; 74 75 /** 76 * Creates a server socket with a user-specified {@code SocketImpl}. 77 * 78 * @param impl an instance of a SocketImpl to use on the ServerSocket. 79 * 80 * @throws NullPointerException if impl is {@code null}. 81 * 82 * @since 12 83 */ 84 protected ServerSocket(SocketImpl impl) { 85 Objects.requireNonNull(impl); 86 this.impl = impl; 87 } 88 89 /** 90 * Creates an unbound server socket. 91 * 92 * @exception IOException IO error when opening the socket. 93 * @revised 1.4 94 */ 95 public ServerSocket() throws IOException { 96 setImpl(); 97 } 98 99 /** 100 * Creates a server socket, bound to the specified port. A port number 101 * of {@code 0} means that the port number is automatically 102 * allocated, typically from an ephemeral port range. This port 103 * number can then be retrieved by calling {@link #getLocalPort getLocalPort}. 104 * <p> 105 * The maximum queue length for incoming connection indications (a 106 * request to connect) is set to {@code 50}. If a connection 107 * indication arrives when the queue is full, the connection is refused. 108 * <p> 109 * If the application has specified a server socket factory, that 110 * factory's {@code createSocketImpl} method is called to create 111 * the actual socket implementation. Otherwise a "plain" socket is created. 112 * <p> 113 * If there is a security manager, 114 * its {@code checkListen} method is called 115 * with the {@code port} argument 116 * as its argument to ensure the operation is allowed. 117 * This could result in a SecurityException. 118 * 119 * 120 * @param port the port number, or {@code 0} to use a port 121 * number that is automatically allocated. 122 * 123 * @exception IOException if an I/O error occurs when opening the socket. 124 * @exception SecurityException 125 * if a security manager exists and its {@code checkListen} 126 * method doesn't allow the operation. 127 * @exception IllegalArgumentException if the port parameter is outside 128 * the specified range of valid port values, which is between 129 * 0 and 65535, inclusive. 130 * 131 * @see java.net.SocketImpl 132 * @see java.net.SocketImplFactory#createSocketImpl() 133 * @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) 134 * @see SecurityManager#checkListen 135 */ 136 public ServerSocket(int port) throws IOException { 137 this(port, 50, null); 138 } 139 140 /** 141 * Creates a server socket and binds it to the specified local port 142 * number, with the specified backlog. 143 * A port number of {@code 0} means that the port number is 144 * automatically allocated, typically from an ephemeral port range. 145 * This port number can then be retrieved by calling 146 * {@link #getLocalPort getLocalPort}. 147 * <p> 148 * The maximum queue length for incoming connection indications (a 149 * request to connect) is set to the {@code backlog} parameter. If 150 * a connection indication arrives when the queue is full, the 151 * connection is refused. 152 * <p> 153 * If the application has specified a server socket factory, that 154 * factory's {@code createSocketImpl} method is called to create 155 * the actual socket implementation. Otherwise a "plain" socket is created. 156 * <p> 157 * If there is a security manager, 158 * its {@code checkListen} method is called 159 * with the {@code port} argument 160 * as its argument to ensure the operation is allowed. 161 * This could result in a SecurityException. 162 * 163 * The {@code backlog} argument is the requested maximum number of 164 * pending connections on the socket. Its exact semantics are implementation 165 * specific. In particular, an implementation may impose a maximum length 166 * or may choose to ignore the parameter altogether. The value provided 167 * should be greater than {@code 0}. If it is less than or equal to 168 * {@code 0}, then an implementation specific default will be used. 169 * 170 * @param port the port number, or {@code 0} to use a port 171 * number that is automatically allocated. 172 * @param backlog requested maximum length of the queue of incoming 173 * connections. 174 * 175 * @exception IOException if an I/O error occurs when opening the socket. 176 * @exception SecurityException 177 * if a security manager exists and its {@code checkListen} 178 * method doesn't allow the operation. 179 * @exception IllegalArgumentException if the port parameter is outside 180 * the specified range of valid port values, which is between 181 * 0 and 65535, inclusive. 182 * 183 * @see java.net.SocketImpl 184 * @see java.net.SocketImplFactory#createSocketImpl() 185 * @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory) 186 * @see SecurityManager#checkListen 187 */ 188 public ServerSocket(int port, int backlog) throws IOException { 189 this(port, backlog, null); 190 } 191 192 /** 193 * Create a server with the specified port, listen backlog, and 194 * local IP address to bind to. The <i>bindAddr</i> argument 195 * can be used on a multi-homed host for a ServerSocket that 196 * will only accept connect requests to one of its addresses. 197 * If <i>bindAddr</i> is null, it will default accepting 198 * connections on any/all local addresses. 199 * The port must be between 0 and 65535, inclusive. 200 * A port number of {@code 0} means that the port number is 201 * automatically allocated, typically from an ephemeral port range. 202 * This port number can then be retrieved by calling 203 * {@link #getLocalPort getLocalPort}. 204 * 205 * <P>If there is a security manager, this method 206 * calls its {@code checkListen} method 207 * with the {@code port} argument 208 * as its argument to ensure the operation is allowed. 209 * This could result in a SecurityException. 210 * 211 * The {@code backlog} argument is the requested maximum number of 212 * pending connections on the socket. Its exact semantics are implementation 213 * specific. In particular, an implementation may impose a maximum length 214 * or may choose to ignore the parameter altogether. The value provided 215 * should be greater than {@code 0}. If it is less than or equal to 216 * {@code 0}, then an implementation specific default will be used. 217 * 218 * @param port the port number, or {@code 0} to use a port 219 * number that is automatically allocated. 220 * @param backlog requested maximum length of the queue of incoming 221 * connections. 222 * @param bindAddr the local InetAddress the server will bind to 223 * 224 * @throws SecurityException if a security manager exists and 225 * its {@code checkListen} method doesn't allow the operation. 226 * 227 * @throws IOException if an I/O error occurs when opening the socket. 228 * @exception IllegalArgumentException if the port parameter is outside 229 * the specified range of valid port values, which is between 230 * 0 and 65535, inclusive. 231 * 232 * @see SocketOptions 233 * @see SocketImpl 234 * @see SecurityManager#checkListen 235 * @since 1.1 236 */ 237 public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { 238 setImpl(); 239 if (port < 0 || port > 0xFFFF) 240 throw new IllegalArgumentException( 241 "Port value out of range: " + port); 242 if (backlog < 1) 243 backlog = 50; 244 try { 245 bind(new InetSocketAddress(bindAddr, port), backlog); 246 } catch(SecurityException e) { 247 close(); 248 throw e; 249 } catch(IOException e) { 250 close(); 251 throw e; 252 } 253 } 254 255 /** 256 * Get the {@code SocketImpl} attached to this socket, creating 257 * it if necessary. 258 * 259 * @return the {@code SocketImpl} attached to that ServerSocket. 260 * @throws SocketException if creation fails. 261 * @since 1.4 262 */ 263 SocketImpl getImpl() throws SocketException { 264 if (!created) 265 createImpl(); 266 return impl; 267 } 268 269 private void setImpl() { 270 SocketImplFactory factory = ServerSocket.factory; 271 if (factory != null) { 272 impl = factory.createSocketImpl(); 273 } else { 274 impl = SocketImpl.createPlatformSocketImpl(true); 275 } 276 } 277 278 /** 279 * Creates the socket implementation. 280 * 281 * @throws IOException if creation fails 282 * @since 1.4 283 */ 284 void createImpl() throws SocketException { 285 if (impl == null) 286 setImpl(); 287 try { 288 impl.create(true); 289 created = true; 290 } catch (IOException e) { 291 throw new SocketException(e.getMessage()); 292 } 293 } 294 295 /** 296 * 297 * Binds the {@code ServerSocket} to a specific address 298 * (IP address and port number). 299 * <p> 300 * If the address is {@code null}, then the system will pick up 301 * an ephemeral port and a valid local address to bind the socket. 302 * 303 * @param endpoint The IP address and port number to bind to. 304 * @throws IOException if the bind operation fails, or if the socket 305 * is already bound. 306 * @throws SecurityException if a {@code SecurityManager} is present and 307 * its {@code checkListen} method doesn't allow the operation. 308 * @throws IllegalArgumentException if endpoint is a 309 * SocketAddress subclass not supported by this socket 310 * @since 1.4 311 */ 312 public void bind(SocketAddress endpoint) throws IOException { 313 bind(endpoint, 50); 314 } 315 316 /** 317 * 318 * Binds the {@code ServerSocket} to a specific address 319 * (IP address and port number). 320 * <p> 321 * If the address is {@code null}, then the system will pick up 322 * an ephemeral port and a valid local address to bind the socket. 323 * <P> 324 * The {@code backlog} argument is the requested maximum number of 325 * pending connections on the socket. Its exact semantics are implementation 326 * specific. In particular, an implementation may impose a maximum length 327 * or may choose to ignore the parameter altogether. The value provided 328 * should be greater than {@code 0}. If it is less than or equal to 329 * {@code 0}, then an implementation specific default will be used. 330 * @param endpoint The IP address and port number to bind to. 331 * @param backlog requested maximum length of the queue of 332 * incoming connections. 333 * @throws IOException if the bind operation fails, or if the socket 334 * is already bound. 335 * @throws SecurityException if a {@code SecurityManager} is present and 336 * its {@code checkListen} method doesn't allow the operation. 337 * @throws IllegalArgumentException if endpoint is a 338 * SocketAddress subclass not supported by this socket 339 * @since 1.4 340 */ 341 public void bind(SocketAddress endpoint, int backlog) throws IOException { 342 if (isClosed()) 343 throw new SocketException("Socket is closed"); 344 if (isBound()) 345 throw new SocketException("Already bound"); 346 if (endpoint == null) 347 endpoint = new InetSocketAddress(0); 348 if (!(endpoint instanceof InetSocketAddress)) 349 throw new IllegalArgumentException("Unsupported address type"); 350 InetSocketAddress epoint = (InetSocketAddress) endpoint; 351 if (epoint.isUnresolved()) 352 throw new SocketException("Unresolved address"); 353 if (backlog < 1) 354 backlog = 50; 355 try { 356 SecurityManager security = System.getSecurityManager(); 357 if (security != null) 358 security.checkListen(epoint.getPort()); 359 getImpl().bind(epoint.getAddress(), epoint.getPort()); 360 getImpl().listen(backlog); 361 bound = true; 362 } catch(SecurityException e) { 363 bound = false; 364 throw e; 365 } catch(IOException e) { 366 bound = false; 367 throw e; 368 } 369 } 370 371 /** 372 * Returns the local address of this server socket. 373 * <p> 374 * If the socket was bound prior to being {@link #close closed}, 375 * then this method will continue to return the local address 376 * after the socket is closed. 377 * <p> 378 * If there is a security manager set, its {@code checkConnect} method is 379 * called with the local address and {@code -1} as its arguments to see 380 * if the operation is allowed. If the operation is not allowed, 381 * the {@link InetAddress#getLoopbackAddress loopback} address is returned. 382 * 383 * @return the address to which this socket is bound, 384 * or the loopback address if denied by the security manager, 385 * or {@code null} if the socket is unbound. 386 * 387 * @see SecurityManager#checkConnect 388 */ 389 public InetAddress getInetAddress() { 390 if (!isBound()) 391 return null; 392 try { 393 InetAddress in = getImpl().getInetAddress(); 394 SecurityManager sm = System.getSecurityManager(); 395 if (sm != null) 396 sm.checkConnect(in.getHostAddress(), -1); 397 return in; 398 } catch (SecurityException e) { 399 return InetAddress.getLoopbackAddress(); 400 } catch (SocketException e) { 401 // nothing 402 // If we're bound, the impl has been created 403 // so we shouldn't get here 404 } 405 return null; 406 } 407 408 /** 409 * Returns the port number on which this socket is listening. 410 * <p> 411 * If the socket was bound prior to being {@link #close closed}, 412 * then this method will continue to return the port number 413 * after the socket is closed. 414 * 415 * @return the port number to which this socket is listening or 416 * -1 if the socket is not bound yet. 417 */ 418 public int getLocalPort() { 419 if (!isBound()) 420 return -1; 421 try { 422 return getImpl().getLocalPort(); 423 } catch (SocketException e) { 424 // nothing 425 // If we're bound, the impl has been created 426 // so we shouldn't get here 427 } 428 return -1; 429 } 430 431 /** 432 * Returns the address of the endpoint this socket is bound to. 433 * <p> 434 * If the socket was bound prior to being {@link #close closed}, 435 * then this method will continue to return the address of the endpoint 436 * after the socket is closed. 437 * <p> 438 * If there is a security manager set, its {@code checkConnect} method is 439 * called with the local address and {@code -1} as its arguments to see 440 * if the operation is allowed. If the operation is not allowed, 441 * a {@code SocketAddress} representing the 442 * {@link InetAddress#getLoopbackAddress loopback} address and the local 443 * port to which the socket is bound is returned. 444 * 445 * @return a {@code SocketAddress} representing the local endpoint of 446 * this socket, or a {@code SocketAddress} representing the 447 * loopback address if denied by the security manager, 448 * or {@code null} if the socket is not bound yet. 449 * 450 * @see #getInetAddress() 451 * @see #getLocalPort() 452 * @see #bind(SocketAddress) 453 * @see SecurityManager#checkConnect 454 * @since 1.4 455 */ 456 457 public SocketAddress getLocalSocketAddress() { 458 if (!isBound()) 459 return null; 460 return new InetSocketAddress(getInetAddress(), getLocalPort()); 461 } 462 463 /** 464 * Listens for a connection to be made to this socket and accepts 465 * it. The method blocks until a connection is made. 466 * 467 * <p>A new Socket {@code s} is created and, if there 468 * is a security manager, 469 * the security manager's {@code checkAccept} method is called 470 * with {@code s.getInetAddress().getHostAddress()} and 471 * {@code s.getPort()} 472 * as its arguments to ensure the operation is allowed. 473 * This could result in a SecurityException. 474 * 475 * @exception IOException if an I/O error occurs when waiting for a 476 * connection. 477 * @exception SecurityException if a security manager exists and its 478 * {@code checkAccept} method doesn't allow the operation. 479 * @exception SocketTimeoutException if a timeout was previously set with setSoTimeout and 480 * the timeout has been reached. 481 * @exception java.nio.channels.IllegalBlockingModeException 482 * if this socket has an associated channel, the channel is in 483 * non-blocking mode, and there is no connection ready to be 484 * accepted 485 * 486 * @return the new Socket 487 * @see SecurityManager#checkAccept 488 * @revised 1.4 489 * @spec JSR-51 490 */ 491 public Socket accept() throws IOException { 492 if (isClosed()) 493 throw new SocketException("Socket is closed"); 494 if (!isBound()) 495 throw new SocketException("Socket is not bound yet"); 496 Socket s = new Socket((SocketImpl) null); 497 implAccept(s); 498 return s; 499 } 500 501 /** 502 * Subclasses of ServerSocket use this method to override accept() 503 * to return their own subclass of socket. So a FooServerSocket 504 * will typically hand this method an <i>empty</i> FooSocket. On 505 * return from implAccept the FooSocket will be connected to a client. 506 * 507 * @param s the Socket 508 * @throws java.nio.channels.IllegalBlockingModeException 509 * if this socket has an associated channel, 510 * and the channel is in non-blocking mode 511 * @throws IOException if an I/O error occurs when waiting 512 * for a connection. 513 * @since 1.1 514 * @revised 1.4 515 * @spec JSR-51 516 */ 517 protected final void implAccept(Socket s) throws IOException { 518 SocketImpl si = s.impl; 519 520 // Socket has no SocketImpl 521 if (si == null) { 522 si = implAccept(); 523 s.setImpl(si); 524 s.postAccept(); 525 return; 526 } 527 528 // Socket has a SOCKS or HTTP SocketImpl, need delegate 529 if (si instanceof DelegatingSocketImpl) { 530 si = ((DelegatingSocketImpl) si).delegate(); 531 assert si instanceof PlatformSocketImpl; 532 } 533 534 // Accept connection with a platform or custom SocketImpl. 535 // For the platform SocketImpl case: 536 // - the connection is accepted with a new SocketImpl 537 // - the SO_TIMEOUT socket option is copied to the new SocketImpl 538 // - the Socket is connected to the new SocketImpl 539 // - the existing/old SocketImpl is closed 540 // For the custom SocketImpl case, the connection is accepted with the 541 // existing custom SocketImpl. 542 ensureCompatible(si); 543 if (impl instanceof PlatformSocketImpl) { 544 SocketImpl psi = platformImplAccept(); 545 si.copyOptionsTo(psi); 546 s.setImpl(psi); 547 si.closeQuietly(); 548 } else { 549 s.impl = null; // temporarily break connection to impl 550 try { 551 customImplAccept(si); 552 } finally { 553 s.impl = si; // restore connection to impl 554 } 555 } 556 s.postAccept(); 557 } 558 559 /** 560 * Accepts a connection with a new SocketImpl. 561 * @return the new SocketImpl 562 */ 563 private SocketImpl implAccept() throws IOException { 564 if (impl instanceof PlatformSocketImpl) { 565 return platformImplAccept(); 566 } else { 567 // custom server SocketImpl, client SocketImplFactory must be set 568 SocketImplFactory factory = Socket.socketImplFactory(); 569 if (factory == null) { 570 throw new IOException("An instance of " + impl.getClass() + 571 " cannot accept connection with 'null' SocketImpl:" + 572 " client socket implementation factory not set"); 573 } 574 SocketImpl si = factory.createSocketImpl(); 575 customImplAccept(si); 576 return si; 577 } 578 } 579 580 /** 581 * Accepts a connection with a new platform SocketImpl. 582 * @return the new platform SocketImpl 583 */ 584 private SocketImpl platformImplAccept() throws IOException { 585 assert impl instanceof PlatformSocketImpl; 586 587 // create a new platform SocketImpl and accept the connection 588 SocketImpl psi = SocketImpl.createPlatformSocketImpl(false); 589 implAccept(psi); 590 return psi; 591 } 592 593 /** 594 * Accepts a new connection with the given custom SocketImpl. 595 */ 596 private void customImplAccept(SocketImpl si) throws IOException { 597 assert !(impl instanceof PlatformSocketImpl) 598 && !(si instanceof PlatformSocketImpl); 599 600 si.reset(); 601 try { 602 // custom SocketImpl may expect fd/address objects to be created 603 si.fd = new FileDescriptor(); 604 si.address = new InetAddress(); 605 implAccept(si); 606 } catch (Exception e) { 607 si.reset(); 608 throw e; 609 } 610 } 611 612 /** 613 * Accepts a new connection so that the given SocketImpl is connected to 614 * the peer. The SocketImpl and connection are closed if the connection is 615 * denied by the security manager. 616 * @throws IOException if an I/O error occurs 617 * @throws SecurityException if the security manager's checkAccept method fails 618 */ 619 private void implAccept(SocketImpl si) throws IOException { 620 assert !(si instanceof DelegatingSocketImpl); 621 622 // accept a connection 623 impl.accept(si); 624 625 // check permission, close SocketImpl/connection if denied 626 SecurityManager sm = System.getSecurityManager(); 627 if (sm != null) { 628 try { 629 sm.checkAccept(si.getInetAddress().getHostAddress(), si.getPort()); 630 } catch (SecurityException se) { 631 si.close(); 632 throw se; 633 } 634 } 635 } 636 637 /** 638 * Throws IOException if the server SocketImpl and the given client 639 * SocketImpl are not both platform or custom SocketImpls. 640 */ 641 private void ensureCompatible(SocketImpl si) throws IOException { 642 if ((impl instanceof PlatformSocketImpl) != (si instanceof PlatformSocketImpl)) { 643 throw new IOException("An instance of " + impl.getClass() + 644 " cannot accept a connection with an instance of " + si.getClass()); 645 } 646 } 647 648 /** 649 * Closes this socket. 650 * 651 * Any thread currently blocked in {@link #accept()} will throw 652 * a {@link SocketException}. 653 * 654 * <p> If this socket has an associated channel then the channel is closed 655 * as well. 656 * 657 * @exception IOException if an I/O error occurs when closing the socket. 658 * @revised 1.4 659 * @spec JSR-51 660 */ 661 public void close() throws IOException { 662 synchronized(closeLock) { 663 if (isClosed()) 664 return; 665 if (created) 666 impl.close(); 667 closed = true; 668 } 669 } 670 671 /** 672 * Returns the unique {@link java.nio.channels.ServerSocketChannel} object 673 * associated with this socket, if any. 674 * 675 * <p> A server socket will have a channel if, and only if, the channel 676 * itself was created via the {@link 677 * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open} 678 * method. 679 * 680 * @return the server-socket channel associated with this socket, 681 * or {@code null} if this socket was not created 682 * for a channel 683 * 684 * @since 1.4 685 * @spec JSR-51 686 */ 687 public ServerSocketChannel getChannel() { 688 return null; 689 } 690 691 /** 692 * Returns the binding state of the ServerSocket. 693 * 694 * @return true if the ServerSocket successfully bound to an address 695 * @since 1.4 696 */ 697 public boolean isBound() { 698 return bound; 699 } 700 701 /** 702 * Returns the closed state of the ServerSocket. 703 * 704 * @return true if the socket has been closed 705 * @since 1.4 706 */ 707 public boolean isClosed() { 708 synchronized(closeLock) { 709 return closed; 710 } 711 } 712 713 /** 714 * Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the 715 * specified timeout, in milliseconds. With this option set to a non-zero 716 * timeout, a call to accept() for this ServerSocket 717 * will block for only this amount of time. If the timeout expires, 718 * a <B>java.net.SocketTimeoutException</B> is raised, though the 719 * ServerSocket is still valid. The option <B>must</B> be enabled 720 * prior to entering the blocking operation to have effect. The 721 * timeout must be {@code > 0}. 722 * A timeout of zero is interpreted as an infinite timeout. 723 * @param timeout the specified timeout, in milliseconds 724 * @throws SocketException if there is an error in the underlying protocol, 725 * such as a TCP error 726 * @throws IllegalArgumentException if {@code timeout} is negative 727 * @since 1.1 728 * @see #getSoTimeout() 729 */ 730 public synchronized void setSoTimeout(int timeout) throws SocketException { 731 if (isClosed()) 732 throw new SocketException("Socket is closed"); 733 if (timeout < 0) 734 throw new IllegalArgumentException("timeout < 0"); 735 getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout); 736 } 737 738 /** 739 * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}. 740 * 0 returns implies that the option is disabled (i.e., timeout of infinity). 741 * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value 742 * @exception IOException if an I/O error occurs 743 * @since 1.1 744 * @see #setSoTimeout(int) 745 */ 746 public synchronized int getSoTimeout() throws IOException { 747 if (isClosed()) 748 throw new SocketException("Socket is closed"); 749 Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT); 750 /* extra type safety */ 751 if (o instanceof Integer) { 752 return ((Integer) o).intValue(); 753 } else { 754 return 0; 755 } 756 } 757 758 /** 759 * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} 760 * socket option. 761 * <p> 762 * When a TCP connection is closed the connection may remain 763 * in a timeout state for a period of time after the connection 764 * is closed (typically known as the {@code TIME_WAIT} state 765 * or {@code 2MSL} wait state). 766 * For applications using a well known socket address or port 767 * it may not be possible to bind a socket to the required 768 * {@code SocketAddress} if there is a connection in the 769 * timeout state involving the socket address or port. 770 * <p> 771 * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to 772 * binding the socket using {@link #bind(SocketAddress)} allows the socket 773 * to be bound even though a previous connection is in a timeout state. 774 * <p> 775 * When a {@code ServerSocket} is created the initial setting 776 * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined. 777 * Applications can use {@link #getReuseAddress()} to determine the initial 778 * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}. 779 * <p> 780 * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is 781 * enabled or disabled after a socket is bound (See {@link #isBound()}) 782 * is not defined. 783 * 784 * @param on whether to enable or disable the socket option 785 * @exception SocketException if an error occurs enabling or 786 * disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} 787 * socket option, or the socket is closed. 788 * @since 1.4 789 * @see #getReuseAddress() 790 * @see #bind(SocketAddress) 791 * @see #isBound() 792 * @see #isClosed() 793 */ 794 public void setReuseAddress(boolean on) throws SocketException { 795 if (isClosed()) 796 throw new SocketException("Socket is closed"); 797 getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on)); 798 } 799 800 /** 801 * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled. 802 * 803 * @return a {@code boolean} indicating whether or not 804 * {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled. 805 * @exception SocketException if there is an error 806 * in the underlying protocol, such as a TCP error. 807 * @since 1.4 808 * @see #setReuseAddress(boolean) 809 */ 810 public boolean getReuseAddress() throws SocketException { 811 if (isClosed()) 812 throw new SocketException("Socket is closed"); 813 return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue(); 814 } 815 816 /** 817 * Returns the implementation address and implementation port of 818 * this socket as a {@code String}. 819 * <p> 820 * If there is a security manager set, its {@code checkConnect} method is 821 * called with the local address and {@code -1} as its arguments to see 822 * if the operation is allowed. If the operation is not allowed, 823 * an {@code InetAddress} representing the 824 * {@link InetAddress#getLoopbackAddress loopback} address is returned as 825 * the implementation address. 826 * 827 * @return a string representation of this socket. 828 */ 829 public String toString() { 830 if (!isBound()) 831 return "ServerSocket[unbound]"; 832 InetAddress in; 833 if (System.getSecurityManager() != null) 834 in = InetAddress.getLoopbackAddress(); 835 else 836 in = impl.getInetAddress(); 837 return "ServerSocket[addr=" + in + 838 ",localport=" + impl.getLocalPort() + "]"; 839 } 840 841 /** 842 * The factory for all server sockets. 843 */ 844 private static volatile SocketImplFactory factory; 845 846 /** 847 * Sets the server socket implementation factory for the 848 * application. The factory can be specified only once. 849 * <p> 850 * When an application creates a new server socket, the socket 851 * implementation factory's {@code createSocketImpl} method is 852 * called to create the actual socket implementation. 853 * <p> 854 * Passing {@code null} to the method is a no-op unless the factory 855 * was already set. 856 * <p> 857 * If there is a security manager, this method first calls 858 * the security manager's {@code checkSetFactory} method 859 * to ensure the operation is allowed. 860 * This could result in a SecurityException. 861 * 862 * @param fac the desired factory. 863 * @exception IOException if an I/O error occurs when setting the 864 * socket factory. 865 * @exception SocketException if the factory has already been defined. 866 * @exception SecurityException if a security manager exists and its 867 * {@code checkSetFactory} method doesn't allow the operation. 868 * @see java.net.SocketImplFactory#createSocketImpl() 869 * @see SecurityManager#checkSetFactory 870 */ 871 public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException { 872 if (factory != null) { 873 throw new SocketException("factory already defined"); 874 } 875 SecurityManager security = System.getSecurityManager(); 876 if (security != null) { 877 security.checkSetFactory(); 878 } 879 factory = fac; 880 } 881 882 /** 883 * Sets a default proposed value for the 884 * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets 885 * accepted from this {@code ServerSocket}. The value actually set 886 * in the accepted socket must be determined by calling 887 * {@link Socket#getReceiveBufferSize()} after the socket 888 * is returned by {@link #accept()}. 889 * <p> 890 * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to 891 * set the size of the internal socket receive buffer, and to set the size 892 * of the TCP receive window that is advertised to the remote peer. 893 * <p> 894 * It is possible to change the value subsequently, by calling 895 * {@link Socket#setReceiveBufferSize(int)}. However, if the application 896 * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323 897 * then the proposed value must be set in the ServerSocket <B>before</B> 898 * it is bound to a local address. This implies, that the ServerSocket must be 899 * created with the no-argument constructor, then setReceiveBufferSize() must 900 * be called and lastly the ServerSocket is bound to an address by calling bind(). 901 * <p> 902 * Failure to do this will not cause an error, and the buffer size may be set to the 903 * requested value but the TCP receive window in sockets accepted from 904 * this ServerSocket will be no larger than 64K bytes. 905 * 906 * @exception SocketException if there is an error 907 * in the underlying protocol, such as a TCP error. 908 * 909 * @param size the size to which to set the receive buffer 910 * size. This value must be greater than 0. 911 * 912 * @exception IllegalArgumentException if the 913 * value is 0 or is negative. 914 * 915 * @since 1.4 916 * @see #getReceiveBufferSize 917 */ 918 public synchronized void setReceiveBufferSize (int size) throws SocketException { 919 if (!(size > 0)) { 920 throw new IllegalArgumentException("negative receive size"); 921 } 922 if (isClosed()) 923 throw new SocketException("Socket is closed"); 924 getImpl().setOption(SocketOptions.SO_RCVBUF, size); 925 } 926 927 /** 928 * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option 929 * for this {@code ServerSocket}, that is the proposed buffer size that 930 * will be used for Sockets accepted from this {@code ServerSocket}. 931 * 932 * <p>Note, the value actually set in the accepted socket is determined by 933 * calling {@link Socket#getReceiveBufferSize()}. 934 * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} 935 * option for this {@code Socket}. 936 * @exception SocketException if there is an error 937 * in the underlying protocol, such as a TCP error. 938 * @see #setReceiveBufferSize(int) 939 * @since 1.4 940 */ 941 public synchronized int getReceiveBufferSize() 942 throws SocketException{ 943 if (isClosed()) 944 throw new SocketException("Socket is closed"); 945 int result = 0; 946 Object o = getImpl().getOption(SocketOptions.SO_RCVBUF); 947 if (o instanceof Integer) { 948 result = ((Integer)o).intValue(); 949 } 950 return result; 951 } 952 953 /** 954 * Sets performance preferences for this ServerSocket. 955 * 956 * <p> Sockets use the TCP/IP protocol by default. Some implementations 957 * may offer alternative protocols which have different performance 958 * characteristics than TCP/IP. This method allows the application to 959 * express its own preferences as to how these tradeoffs should be made 960 * when the implementation chooses from the available protocols. 961 * 962 * <p> Performance preferences are described by three integers 963 * whose values indicate the relative importance of short connection time, 964 * low latency, and high bandwidth. The absolute values of the integers 965 * are irrelevant; in order to choose a protocol the values are simply 966 * compared, with larger values indicating stronger preferences. If the 967 * application prefers short connection time over both low latency and high 968 * bandwidth, for example, then it could invoke this method with the values 969 * {@code (1, 0, 0)}. If the application prefers high bandwidth above low 970 * latency, and low latency above short connection time, then it could 971 * invoke this method with the values {@code (0, 1, 2)}. 972 * 973 * <p> Invoking this method after this socket has been bound 974 * will have no effect. This implies that in order to use this capability 975 * requires the socket to be created with the no-argument constructor. 976 * 977 * @param connectionTime 978 * An {@code int} expressing the relative importance of a short 979 * connection time 980 * 981 * @param latency 982 * An {@code int} expressing the relative importance of low 983 * latency 984 * 985 * @param bandwidth 986 * An {@code int} expressing the relative importance of high 987 * bandwidth 988 * 989 * @since 1.5 990 */ 991 public void setPerformancePreferences(int connectionTime, 992 int latency, 993 int bandwidth) 994 { 995 /* Not implemented yet */ 996 } 997 998 /** 999 * Sets the value of a socket option. 1000 * 1001 * @param <T> The type of the socket option value 1002 * @param name The socket option 1003 * @param value The value of the socket option. A value of {@code null} 1004 * may be valid for some options. 1005 * @return this ServerSocket 1006 * 1007 * @throws UnsupportedOperationException if the server socket does not 1008 * support the option. 1009 * 1010 * @throws IllegalArgumentException if the value is not valid for 1011 * the option. 1012 * 1013 * @throws IOException if an I/O error occurs, or if the socket is closed. 1014 * 1015 * @throws NullPointerException if name is {@code null} 1016 * 1017 * @throws SecurityException if a security manager is set and if the socket 1018 * option requires a security permission and if the caller does 1019 * not have the required permission. 1020 * {@link java.net.StandardSocketOptions StandardSocketOptions} 1021 * do not require any security permission. 1022 * 1023 * @since 9 1024 */ 1025 public <T> ServerSocket setOption(SocketOption<T> name, T value) 1026 throws IOException 1027 { 1028 getImpl().setOption(name, value); 1029 return this; 1030 } 1031 1032 /** 1033 * Returns the value of a socket option. 1034 * 1035 * @param <T> The type of the socket option value 1036 * @param name The socket option 1037 * 1038 * @return The value of the socket option. 1039 * 1040 * @throws UnsupportedOperationException if the server socket does not 1041 * support the option. 1042 * 1043 * @throws IOException if an I/O error occurs, or if the socket is closed. 1044 * 1045 * @throws NullPointerException if name is {@code null} 1046 * 1047 * @throws SecurityException if a security manager is set and if the socket 1048 * option requires a security permission and if the caller does 1049 * not have the required permission. 1050 * {@link java.net.StandardSocketOptions StandardSocketOptions} 1051 * do not require any security permission. 1052 * 1053 * @since 9 1054 */ 1055 public <T> T getOption(SocketOption<T> name) throws IOException { 1056 return getImpl().getOption(name); 1057 } 1058 1059 // cache of unmodifiable impl options. Possibly set racy, in impl we trust 1060 private volatile Set<SocketOption<?>> options; 1061 1062 /** 1063 * Returns a set of the socket options supported by this server socket. 1064 * 1065 * This method will continue to return the set of options even after 1066 * the socket has been closed. 1067 * 1068 * @return A set of the socket options supported by this socket. This set 1069 * may be empty if the socket's SocketImpl cannot be created. 1070 * 1071 * @since 9 1072 */ 1073 public Set<SocketOption<?>> supportedOptions() { 1074 Set<SocketOption<?>> so = options; 1075 if (so != null) 1076 return so; 1077 1078 try { 1079 SocketImpl impl = getImpl(); 1080 options = Collections.unmodifiableSet(impl.supportedOptions()); 1081 } catch (IOException e) { 1082 options = Collections.emptySet(); 1083 } 1084 return options; 1085 } 1086 1087 static { 1088 SharedSecrets.setJavaNetSocketAccess( 1089 new JavaNetSocketAccess() { 1090 @Override 1091 public ServerSocket newServerSocket(SocketImpl impl) { 1092 return new ServerSocket(impl); 1093 } 1094 1095 @Override 1096 public SocketImpl newSocketImpl(Class<? extends SocketImpl> implClass) { 1097 try { 1098 Constructor<? extends SocketImpl> ctor = 1099 implClass.getDeclaredConstructor(); 1100 return ctor.newInstance(); 1101 } catch (NoSuchMethodException | InstantiationException | 1102 IllegalAccessException | InvocationTargetException e) { 1103 throw new AssertionError(e); 1104 } 1105 } 1106 } 1107 ); 1108 } 1109 }