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