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