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