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 * @hide 255 */ 256 // Android-changed: Make ctor public and @hide, for internal use. 257 public SocketImpl getImpl() throws SocketException { 258 if (!created) 259 createImpl(); 260 return impl; 261 } 262 263 private void checkOldImpl() { 264 if (impl == null) 265 return; 266 // SocketImpl.connect() is a protected method, therefore we need to use 267 // getDeclaredMethod, therefore we need permission to access the member 268 try { 269 AccessController.doPrivileged( 270 new PrivilegedExceptionAction<Void>() { 271 public Void run() throws NoSuchMethodException { 272 impl.getClass().getDeclaredMethod("connect", 273 SocketAddress.class, 274 int.class); 275 return null; 276 } 277 }); 278 } catch (java.security.PrivilegedActionException e) { 279 oldImpl = true; 280 } 281 } 282 283 private void setImpl() { 284 if (factory != null) { 285 impl = factory.createSocketImpl(); 286 checkOldImpl(); 287 } else { 288 // No need to do a checkOldImpl() here, we know it's an up to date 289 // SocketImpl! 290 impl = new SocksSocketImpl(); 291 } 292 if (impl != null) 293 impl.setServerSocket(this); 294 } 295 296 /** 297 * Creates the socket implementation. 298 * 299 * @throws IOException if creation fails 300 * @since 1.4 301 */ 302 void createImpl() throws SocketException { 303 if (impl == null) 304 setImpl(); 305 try { 306 impl.create(true); 307 created = true; 308 } catch (IOException e) { 309 throw new SocketException(e.getMessage()); 310 } 311 } 312 313 /** 314 * 315 * Binds the {@code ServerSocket} to a specific address 316 * (IP address and port number). 317 * <p> 318 * If the address is {@code null}, then the system will pick up 319 * an ephemeral port and a valid local address to bind the socket. 320 * <p> 321 * @param endpoint The IP address and port number to bind to. 322 * @throws IOException if the bind operation fails, or if the socket 323 * is already bound. 324 * @throws SecurityException if a {@code SecurityManager} is present and 325 * its {@code checkListen} method doesn't allow the operation. 326 * @throws IllegalArgumentException if endpoint is a 327 * SocketAddress subclass not supported by this socket 328 * @since 1.4 329 */ 330 public void bind(SocketAddress endpoint) throws IOException { 331 bind(endpoint, 50); 332 } 333 334 /** 335 * 336 * Binds the {@code ServerSocket} to a specific address 337 * (IP address and port number). 338 * <p> 339 * If the address is {@code null}, then the system will pick up 340 * an ephemeral port and a valid local address to bind the socket. 341 * <P> 342 * The {@code backlog} argument is the requested maximum number of 343 * pending connections on the socket. Its exact semantics are implementation 344 * specific. In particular, an implementation may impose a maximum length 345 * or may choose to ignore the parameter altogther. The value provided 346 * should be greater than {@code 0}. If it is less than or equal to 347 * {@code 0}, then an implementation specific default will be used. 348 * @param endpoint The IP address and port number to bind to. 349 * @param backlog requested maximum length of the queue of 350 * incoming connections. 351 * @throws IOException if the bind operation fails, or if the socket 352 * is already bound. 353 * @throws SecurityException if a {@code SecurityManager} is present and 354 * its {@code checkListen} method doesn't allow the operation. 355 * @throws IllegalArgumentException if endpoint is a 356 * SocketAddress subclass not supported by this socket 357 * @since 1.4 358 */ 359 public void bind(SocketAddress endpoint, int backlog) throws IOException { 360 if (isClosed()) 361 throw new SocketException("Socket is closed"); 362 if (!oldImpl && isBound()) 363 throw new SocketException("Already bound"); 364 if (endpoint == null) 365 endpoint = new InetSocketAddress(0); 366 if (!(endpoint instanceof InetSocketAddress)) 367 throw new IllegalArgumentException("Unsupported address type"); 368 InetSocketAddress epoint = (InetSocketAddress) endpoint; 369 if (epoint.isUnresolved()) 370 throw new SocketException("Unresolved address"); 371 if (backlog < 1) 372 backlog = 50; 373 try { 374 SecurityManager security = System.getSecurityManager(); 375 if (security != null) 376 security.checkListen(epoint.getPort()); 377 getImpl().bind(epoint.getAddress(), epoint.getPort()); 378 getImpl().listen(backlog); 379 bound = true; 380 } catch(SecurityException e) { 381 bound = false; 382 throw e; 383 } catch(IOException e) { 384 bound = false; 385 throw e; 386 } 387 } 388 389 /** 390 * Returns the local address of this server socket. 391 * <p> 392 * If the socket was bound prior to being {@link #close closed}, 393 * then this method will continue to return the local address 394 * after the socket is closed. 395 * <p> 396 * If there is a security manager set, its {@code checkConnect} method is 397 * called with the local address and {@code -1} as its arguments to see 398 * if the operation is allowed. If the operation is not allowed, 399 * the {@link InetAddress#getLoopbackAddress loopback} address is returned. 400 * 401 * @return the address to which this socket is bound, 402 * or the loopback address if denied by the security manager, 403 * or {@code null} if the socket is unbound. 404 * 405 * @see SecurityManager#checkConnect 406 */ 407 public InetAddress getInetAddress() { 408 if (!isBound()) 409 return null; 410 try { 411 InetAddress in = getImpl().getInetAddress(); 412 SecurityManager sm = System.getSecurityManager(); 413 if (sm != null) 414 sm.checkConnect(in.getHostAddress(), -1); 415 return in; 416 } catch (SecurityException e) { 417 return InetAddress.getLoopbackAddress(); 418 } catch (SocketException e) { 419 // nothing 420 // If we're bound, the impl has been created 421 // so we shouldn't get here 422 } 423 return null; 424 } 425 426 /** 427 * Returns the port number on which this socket is listening. 428 * <p> 429 * If the socket was bound prior to being {@link #close closed}, 430 * then this method will continue to return the port number 431 * after the socket is closed. 432 * 433 * @return the port number to which this socket is listening or 434 * -1 if the socket is not bound yet. 435 */ 436 public int getLocalPort() { 437 if (!isBound()) 438 return -1; 439 try { 440 return getImpl().getLocalPort(); 441 } catch (SocketException e) { 442 // nothing 443 // If we're bound, the impl has been created 444 // so we shouldn't get here 445 } 446 return -1; 447 } 448 449 /** 450 * Returns the address of the endpoint this socket is bound to. 451 * <p> 452 * If the socket was bound prior to being {@link #close closed}, 453 * then this method will continue to return the address of the endpoint 454 * after the socket is closed. 455 * <p> 456 * If there is a security manager set, its {@code checkConnect} method is 457 * called with the local address and {@code -1} as its arguments to see 458 * if the operation is allowed. If the operation is not allowed, 459 * a {@code SocketAddress} representing the 460 * {@link InetAddress#getLoopbackAddress loopback} address and the local 461 * port to which the socket is bound is returned. 462 * 463 * @return a {@code SocketAddress} representing the local endpoint of 464 * this socket, or a {@code SocketAddress} representing the 465 * loopback address if denied by the security manager, 466 * or {@code null} if the socket is not bound yet. 467 * 468 * @see #getInetAddress() 469 * @see #getLocalPort() 470 * @see #bind(SocketAddress) 471 * @see SecurityManager#checkConnect 472 * @since 1.4 473 */ 474 475 public SocketAddress getLocalSocketAddress() { 476 if (!isBound()) 477 return null; 478 return new InetSocketAddress(getInetAddress(), getLocalPort()); 479 } 480 481 /** 482 * Listens for a connection to be made to this socket and accepts 483 * it. The method blocks until a connection is made. 484 * 485 * <p>A new Socket {@code s} is created and, if there 486 * is a security manager, 487 * the security manager's {@code checkAccept} method is called 488 * with {@code s.getInetAddress().getHostAddress()} and 489 * {@code s.getPort()} 490 * as its arguments to ensure the operation is allowed. 491 * This could result in a SecurityException. 492 * 493 * @exception IOException if an I/O error occurs when waiting for a 494 * connection. 495 * @exception SecurityException if a security manager exists and its 496 * {@code checkAccept} method doesn't allow the operation. 497 * @exception SocketTimeoutException if a timeout was previously set with setSoTimeout and 498 * the timeout has been reached. 499 * @exception java.nio.channels.IllegalBlockingModeException 500 * if this socket has an associated channel, the channel is in 501 * non-blocking mode, and there is no connection ready to be 502 * accepted 503 * 504 * @return the new Socket 505 * @see SecurityManager#checkAccept 506 * @revised 1.4 507 * @spec JSR-51 508 */ 509 public Socket accept() throws IOException { 510 if (isClosed()) 511 throw new SocketException("Socket is closed"); 512 if (!isBound()) 513 throw new SocketException("Socket is not bound yet"); 514 Socket s = new Socket((SocketImpl) null); 515 implAccept(s); 516 return s; 517 } 518 519 /** 520 * Subclasses of ServerSocket use this method to override accept() 521 * to return their own subclass of socket. So a FooServerSocket 522 * will typically hand this method an <i>empty</i> FooSocket. On 523 * return from implAccept the FooSocket will be connected to a client. 524 * 525 * @param s the Socket 526 * @throws java.nio.channels.IllegalBlockingModeException 527 * if this socket has an associated channel, 528 * and the channel is in non-blocking mode 529 * @throws IOException if an I/O error occurs when waiting 530 * for a connection. 531 * @since JDK1.1 532 * @revised 1.4 533 * @spec JSR-51 534 */ 535 protected final void implAccept(Socket s) throws IOException { 536 SocketImpl si = null; 537 try { 538 if (s.impl == null) 539 s.setImpl(); 540 else { 541 s.impl.reset(); 542 } 543 si = s.impl; 544 s.impl = null; 545 si.address = new InetAddress(); 546 si.fd = new FileDescriptor(); 547 getImpl().accept(si); 548 549 SecurityManager security = System.getSecurityManager(); 550 if (security != null) { 551 security.checkAccept(si.getInetAddress().getHostAddress(), 552 si.getPort()); 553 } 554 } catch (IOException e) { 555 if (si != null) 556 si.reset(); 557 s.impl = si; 558 throw e; 559 } catch (SecurityException e) { 560 if (si != null) 561 si.reset(); 562 s.impl = si; 563 throw e; 564 } 565 s.impl = si; 566 s.postAccept(); 567 } 568 569 /** 570 * Closes this socket. 571 * 572 * Any thread currently blocked in {@link #accept()} will throw 573 * a {@link SocketException}. 574 * 575 * <p> If this socket has an associated channel then the channel is closed 576 * as well. 577 * 578 * @exception IOException if an I/O error occurs when closing the socket. 579 * @revised 1.4 580 * @spec JSR-51 581 */ 582 public void close() throws IOException { 583 synchronized(closeLock) { 584 if (isClosed()) 585 return; 586 if (created) 587 impl.close(); 588 closed = true; 589 } 590 } 591 592 /** 593 * Returns the unique {@link java.nio.channels.ServerSocketChannel} object 594 * associated with this socket, if any. 595 * 596 * <p> A server socket will have a channel if, and only if, the channel 597 * itself was created via the {@link 598 * java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open} 599 * method. 600 * 601 * @return the server-socket channel associated with this socket, 602 * or {@code null} if this socket was not created 603 * for a channel 604 * 605 * @since 1.4 606 * @spec JSR-51 607 */ 608 public ServerSocketChannel getChannel() { 609 return null; 610 } 611 612 /** 613 * Returns the binding state of the ServerSocket. 614 * 615 * @return true if the ServerSocket successfully bound to an address 616 * @since 1.4 617 */ 618 public boolean isBound() { 619 // Before 1.3 ServerSockets were always bound during creation 620 return bound || oldImpl; 621 } 622 623 /** 624 * Returns the closed state of the ServerSocket. 625 * 626 * @return true if the socket has been closed 627 * @since 1.4 628 */ 629 public boolean isClosed() { 630 synchronized(closeLock) { 631 return closed; 632 } 633 } 634 635 /** 636 * Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the 637 * specified timeout, in milliseconds. With this option set to a non-zero 638 * timeout, a call to accept() for this ServerSocket 639 * will block for only this amount of time. If the timeout expires, 640 * a <B>java.net.SocketTimeoutException</B> is raised, though the 641 * ServerSocket is still valid. The option <B>must</B> be enabled 642 * prior to entering the blocking operation to have effect. The 643 * timeout must be {@code > 0}. 644 * A timeout of zero is interpreted as an infinite timeout. 645 * @param timeout the specified timeout, in milliseconds 646 * @exception SocketException if there is an error in 647 * the underlying protocol, such as a TCP error. 648 * @since JDK1.1 649 * @see #getSoTimeout() 650 */ 651 public synchronized void setSoTimeout(int timeout) throws SocketException { 652 if (isClosed()) 653 throw new SocketException("Socket is closed"); 654 getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout)); 655 } 656 657 /** 658 * Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}. 659 * 0 returns implies that the option is disabled (i.e., timeout of infinity). 660 * @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value 661 * @exception IOException if an I/O error occurs 662 * @since JDK1.1 663 * @see #setSoTimeout(int) 664 */ 665 public synchronized int getSoTimeout() throws IOException { 666 if (isClosed()) 667 throw new SocketException("Socket is closed"); 668 Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT); 669 /* extra type safety */ 670 if (o instanceof Integer) { 671 return ((Integer) o).intValue(); 672 } else { 673 return 0; 674 } 675 } 676 677 /** 678 * Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} 679 * socket option. 680 * <p> 681 * When a TCP connection is closed the connection may remain 682 * in a timeout state for a period of time after the connection 683 * is closed (typically known as the {@code TIME_WAIT} state 684 * or {@code 2MSL} wait state). 685 * For applications using a well known socket address or port 686 * it may not be possible to bind a socket to the required 687 * {@code SocketAddress} if there is a connection in the 688 * timeout state involving the socket address or port. 689 * <p> 690 * Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to 691 * binding the socket using {@link #bind(SocketAddress)} allows the socket 692 * to be bound even though a previous connection is in a timeout state. 693 * <p> 694 * When a {@code ServerSocket} is created the initial setting 695 * of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined. 696 * Applications can use {@link #getReuseAddress()} to determine the initial 697 * setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}. 698 * <p> 699 * The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is 700 * enabled or disabled after a socket is bound (See {@link #isBound()}) 701 * is not defined. 702 * 703 * @param on whether to enable or disable the socket option 704 * @exception SocketException if an error occurs enabling or 705 * disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} 706 * socket option, or the socket is closed. 707 * @since 1.4 708 * @see #getReuseAddress() 709 * @see #bind(SocketAddress) 710 * @see #isBound() 711 * @see #isClosed() 712 */ 713 public void setReuseAddress(boolean on) throws SocketException { 714 if (isClosed()) 715 throw new SocketException("Socket is closed"); 716 getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on)); 717 } 718 719 /** 720 * Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled. 721 * 722 * @return a {@code boolean} indicating whether or not 723 * {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled. 724 * @exception SocketException if there is an error 725 * in the underlying protocol, such as a TCP error. 726 * @since 1.4 727 * @see #setReuseAddress(boolean) 728 */ 729 public boolean getReuseAddress() throws SocketException { 730 if (isClosed()) 731 throw new SocketException("Socket is closed"); 732 return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue(); 733 } 734 735 /** 736 * Returns the implementation address and implementation port of 737 * this socket as a {@code String}. 738 * <p> 739 * If there is a security manager set, its {@code checkConnect} method is 740 * called with the local address and {@code -1} as its arguments to see 741 * if the operation is allowed. If the operation is not allowed, 742 * an {@code InetAddress} representing the 743 * {@link InetAddress#getLoopbackAddress loopback} address is returned as 744 * the implementation address. 745 * 746 * @return a string representation of this socket. 747 */ 748 public String toString() { 749 if (!isBound()) 750 return "ServerSocket[unbound]"; 751 InetAddress in; 752 if (System.getSecurityManager() != null) 753 in = InetAddress.getLoopbackAddress(); 754 else 755 in = impl.getInetAddress(); 756 return "ServerSocket[addr=" + in + 757 ",localport=" + impl.getLocalPort() + "]"; 758 } 759 760 void setBound() { 761 bound = true; 762 } 763 764 void setCreated() { 765 created = true; 766 } 767 768 /** 769 * The factory for all server sockets. 770 */ 771 private static SocketImplFactory factory = null; 772 773 /** 774 * Sets the server socket implementation factory for the 775 * application. The factory can be specified only once. 776 * <p> 777 * When an application creates a new server socket, the socket 778 * implementation factory's {@code createSocketImpl} method is 779 * called to create the actual socket implementation. 780 * <p> 781 * Passing {@code null} to the method is a no-op unless the factory 782 * was already set. 783 * <p> 784 * If there is a security manager, this method first calls 785 * the security manager's {@code checkSetFactory} method 786 * to ensure the operation is allowed. 787 * This could result in a SecurityException. 788 * 789 * @param fac the desired factory. 790 * @exception IOException if an I/O error occurs when setting the 791 * socket factory. 792 * @exception SocketException if the factory has already been defined. 793 * @exception SecurityException if a security manager exists and its 794 * {@code checkSetFactory} method doesn't allow the operation. 795 * @see java.net.SocketImplFactory#createSocketImpl() 796 * @see SecurityManager#checkSetFactory 797 */ 798 public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException { 799 if (factory != null) { 800 throw new SocketException("factory already defined"); 801 } 802 SecurityManager security = System.getSecurityManager(); 803 if (security != null) { 804 security.checkSetFactory(); 805 } 806 factory = fac; 807 } 808 809 /** 810 * Sets a default proposed value for the 811 * {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets 812 * accepted from this {@code ServerSocket}. The value actually set 813 * in the accepted socket must be determined by calling 814 * {@link Socket#getReceiveBufferSize()} after the socket 815 * is returned by {@link #accept()}. 816 * <p> 817 * The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to 818 * set the size of the internal socket receive buffer, and to set the size 819 * of the TCP receive window that is advertized to the remote peer. 820 * <p> 821 * It is possible to change the value subsequently, by calling 822 * {@link Socket#setReceiveBufferSize(int)}. However, if the application 823 * wishes to allow a receive window larger than 64K bytes, as defined by RFC1323 824 * then the proposed value must be set in the ServerSocket <B>before</B> 825 * it is bound to a local address. This implies, that the ServerSocket must be 826 * created with the no-argument constructor, then setReceiveBufferSize() must 827 * be called and lastly the ServerSocket is bound to an address by calling bind(). 828 * <p> 829 * Failure to do this will not cause an error, and the buffer size may be set to the 830 * requested value but the TCP receive window in sockets accepted from 831 * this ServerSocket will be no larger than 64K bytes. 832 * 833 * @exception SocketException if there is an error 834 * in the underlying protocol, such as a TCP error. 835 * 836 * @param size the size to which to set the receive buffer 837 * size. This value must be greater than 0. 838 * 839 * @exception IllegalArgumentException if the 840 * value is 0 or is negative. 841 * 842 * @since 1.4 843 * @see #getReceiveBufferSize 844 */ 845 public synchronized void setReceiveBufferSize (int size) throws SocketException { 846 if (!(size > 0)) { 847 throw new IllegalArgumentException("negative receive size"); 848 } 849 if (isClosed()) 850 throw new SocketException("Socket is closed"); 851 getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size)); 852 } 853 854 /** 855 * Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option 856 * for this {@code ServerSocket}, that is the proposed buffer size that 857 * will be used for Sockets accepted from this {@code ServerSocket}. 858 * 859 * <p>Note, the value actually set in the accepted socket is determined by 860 * calling {@link Socket#getReceiveBufferSize()}. 861 * @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} 862 * option for this {@code Socket}. 863 * @exception SocketException if there is an error 864 * in the underlying protocol, such as a TCP error. 865 * @see #setReceiveBufferSize(int) 866 * @since 1.4 867 */ 868 public synchronized int getReceiveBufferSize() 869 throws SocketException{ 870 if (isClosed()) 871 throw new SocketException("Socket is closed"); 872 int result = 0; 873 Object o = getImpl().getOption(SocketOptions.SO_RCVBUF); 874 if (o instanceof Integer) { 875 result = ((Integer)o).intValue(); 876 } 877 return result; 878 } 879 880 /** 881 * Sets performance preferences for this ServerSocket. 882 * 883 * <p> Sockets use the TCP/IP protocol by default. Some implementations 884 * may offer alternative protocols which have different performance 885 * characteristics than TCP/IP. This method allows the application to 886 * express its own preferences as to how these tradeoffs should be made 887 * when the implementation chooses from the available protocols. 888 * 889 * <p> Performance preferences are described by three integers 890 * whose values indicate the relative importance of short connection time, 891 * low latency, and high bandwidth. The absolute values of the integers 892 * are irrelevant; in order to choose a protocol the values are simply 893 * compared, with larger values indicating stronger preferences. If the 894 * application prefers short connection time over both low latency and high 895 * bandwidth, for example, then it could invoke this method with the values 896 * {@code (1, 0, 0)}. If the application prefers high bandwidth above low 897 * latency, and low latency above short connection time, then it could 898 * invoke this method with the values {@code (0, 1, 2)}. 899 * 900 * <p> Invoking this method after this socket has been bound 901 * will have no effect. This implies that in order to use this capability 902 * requires the socket to be created with the no-argument constructor. 903 * 904 * @param connectionTime 905 * An {@code int} expressing the relative importance of a short 906 * connection time 907 * 908 * @param latency 909 * An {@code int} expressing the relative importance of low 910 * latency 911 * 912 * @param bandwidth 913 * An {@code int} expressing the relative importance of high 914 * bandwidth 915 * 916 * @since 1.5 917 */ 918 public void setPerformancePreferences(int connectionTime, 919 int latency, 920 int bandwidth) 921 { 922 /* Not implemented yet */ 923 } 924 925 // Android-added: getFileDescriptor$(), for testing / internal use. 926 /** 927 * @hide internal use only 928 */ 929 public FileDescriptor getFileDescriptor$() { 930 return impl.getFileDescriptor(); 931 } 932 } 933