Socket.java 33 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Socket.java -- Client socket implementation
   Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
 
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
37

38
package java.net;
Tom Tromey committed
39

40 41 42
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
43
import java.nio.channels.SocketChannel;
44
import java.nio.channels.IllegalBlockingModeException;
Tom Tromey committed
45

46 47 48
/* Written using on-line Java Platform 1.2 API Specification.
 * Status:  I believe all methods are implemented.
 */
Tom Tromey committed
49 50

/**
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
 * This class models a client site socket.  A socket is a TCP/IP endpoint
 * for network communications conceptually similar to a file handle.
 * <p>
 * This class does not actually do any work.  Instead, it redirects all of
 * its calls to a socket implementation object which implements the
 * <code>SocketImpl</code> interface.  The implementation class is 
 * instantiated by factory class that implements the 
 * <code>SocketImplFactory interface</code>.  A default
 * factory is provided, however the factory may be set by a call to
 * the <code>setSocketImplFactory</code> method.  Note that this may only be 
 * done once per virtual machine.  If a subsequent attempt is made to set the
 * factory, a <code>SocketException</code> will be thrown.
 *
 * @author Aaron M. Renn (arenn@urbanophile.com)
 * @author Per Bothner (bothner@cygnus.com)
 */
Tom Tromey committed
67 68
public class Socket
{
69 70 71 72 73 74 75

  // Class Variables

  /**
   * This is the user SocketImplFactory for this class.  If this variable is
   * null, a default factory is used.
   */
Tom Tromey committed
76
  static SocketImplFactory factory;
77 78 79 80 81 82

  // Instance Variables

  /**
   * The implementation object to which calls are redirected
   */
Tom Tromey committed
83 84
  SocketImpl impl;

85 86 87
  private boolean inputShutdown;
  private boolean outputShutdown;

88
  SocketChannel ch; // this field must have been set if created by SocketChannel
89

90 91
  private boolean closed = false;

92 93 94 95
  /**
   * Initializes a new instance of <code>Socket</code> object without 
   * connecting to a remote host.  This useful for subclasses of socket that 
   * might want this behavior.
96 97
   *
   * @specnote This constructor is public since JDK 1.4
98
   * @since 1.1
99
   */
100
  public Socket ()
Tom Tromey committed
101
  {
102 103 104 105
    if (factory != null)
      impl = factory.createSocketImpl();
    else
      impl = new PlainSocketImpl();
106 107 108

    inputShutdown = false;
    outputShutdown = false;
Tom Tromey committed
109 110
  }

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
  /**
   * Initializes a new instance of <code>Socket</code> object without
   * connecting to a remote host.  This is useful for subclasses of socket
   * that might want this behavior.  
   * <p>
   * Additionally, this socket will be created using the supplied
   * implementation class instead the default class or one returned by a
   * factory.  This value can be <code>null</code>, but if it is, all instance
   * methods in <code>Socket</code> should be overridden because most of them
   * rely on this value being populated.
   *
   * @param impl The <code>SocketImpl</code> to use for this
   *             <code>Socket</code>
   *
   * @exception SocketException If an error occurs
126 127
   *
   * @since 1.1
128
   */
Tom Tromey committed
129 130 131
  protected Socket (SocketImpl impl) throws SocketException
  {
    this.impl = impl;
132 133
    this.inputShutdown = false;
    this.outputShutdown = false;
Tom Tromey committed
134 135
  }

136 137 138 139 140 141 142 143 144 145
  /**
   * Initializes a new instance of <code>Socket</code> and connects to the 
   * hostname and port specified as arguments.
   *
   * @param host The name of the host to connect to
   * @param port The port number to connect to
   *
   * @exception UnknownHostException If the hostname cannot be resolved to a
   * network address.
   * @exception IOException If an error occurs
146 147
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
148
   */
Tom Tromey committed
149 150 151
  public Socket (String host, int port)
    throws UnknownHostException, IOException
  {
152
    this(InetAddress.getByName(host), port, null, 0, true);
Tom Tromey committed
153 154
  }

155 156 157 158 159 160 161 162
  /**
   * Initializes a new instance of <code>Socket</code> and connects to the 
   * address and port number specified as arguments.
   *
   * @param address The address to connect to
   * @param port The port number to connect to
   *
   * @exception IOException If an error occurs
163 164
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
165
   */
Tom Tromey committed
166 167 168
  public Socket (InetAddress address, int port)
    throws IOException 
  {
169
    this(address, port, null, 0, true);
Tom Tromey committed
170 171
  }

172 173 174 175 176 177 178 179 180 181 182 183 184 185
  /**
   * Initializes a new instance of <code>Socket</code> that connects to the 
   * named host on the specified port and binds to the specified local address 
   * and port.
   *
   * @param host The name of the remote host to connect to.
   * @param port The remote port to connect to.
   * @param loadAddr The local address to bind to.
   * @param localPort The local port to bind to.
   *
   * @exception SecurityException If the <code>SecurityManager</code>
   * exists and does not allow a connection to the specified host/port or
   * binding to the specified local host/port.
   * @exception IOException If a connection error occurs.
186 187
   *
   * @since 1.1
188
   */
Tom Tromey committed
189 190 191
  public Socket (String host, int port,
		 InetAddress localAddr, int localPort) throws IOException
  {
192
    this(InetAddress.getByName(host), port, localAddr, localPort, true);
Tom Tromey committed
193 194
  }

195 196 197 198 199 200 201 202 203 204 205
  /**
   * Initializes a new instance of <code>Socket</code> and connects to the 
   * address and port number specified as arguments, plus binds to the 
   * specified local address and port.
   *
   * @param address The remote address to connect to
   * @param port The remote port to connect to
   * @param localAddr The local address to connect to
   * @param localPort The local port to connect to
   *
   * @exception IOException If an error occurs
206 207
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
208 209
   *
   * @since 1.1
210
   */
Tom Tromey committed
211 212 213
  public Socket (InetAddress address, int port,
		 InetAddress localAddr, int localPort) throws IOException
  {
214
    this(address, port, localAddr, localPort, true);
Tom Tromey committed
215 216 217
  }

  /**
218 219 220 221 222 223 224 225 226 227 228
   * Initializes a new instance of <code>Socket</code> and connects to the 
   * hostname and port specified as arguments.  If the stream argument is set 
   * to <code>true</code>, then a stream socket is created.  If it is 
   * <code>false</code>, a datagram socket is created.
   *
   * @param host The name of the host to connect to
   * @param port The port to connect to
   * @param stream <code>true</code> for a stream socket, <code>false</code>
   * for a datagram socket
   *
   * @exception IOException If an error occurs
229 230
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
231 232 233
   *
   * @deprecated Use the <code>DatagramSocket</code> class to create
   * datagram oriented sockets.
Tom Tromey committed
234 235 236
   */
  public Socket (String host, int port, boolean stream) throws IOException
  {
237
    this(InetAddress.getByName(host), port, null, 0, stream);
Tom Tromey committed
238 239 240
  }

  /**
241 242 243 244 245 246 247 248 249 250 251
   * Initializes a new instance of <code>Socket</code> and connects to the 
   * address and port number specified as arguments.  If the stream param is 
   * <code>true</code>, a stream socket will be created, otherwise a datagram 
   * socket is created.
   *
   * @param host The address to connect to
   * @param port The port number to connect to
   * @param stream <code>true</code> to create a stream socket, 
   * <code>false</code> to create a datagram socket.
   *
   * @exception IOException If an error occurs
252 253
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
254 255 256
   *
   * @deprecated Use the <code>DatagramSocket</code> class to create
   * datagram oriented sockets.
Tom Tromey committed
257 258 259
   */
  public Socket (InetAddress host, int port, boolean stream) throws IOException
  {
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    this(host, port, null, 0, stream);
  }

  /**
   * This constructor is where the real work takes place.  Connect to the
   * specified address and port.  Use default local values if not specified,
   * otherwise use the local host and port passed in.  Create as stream or
   * datagram based on "stream" argument.
   * <p>
   *
   * @param raddr The remote address to connect to
   * @param rport The remote port to connect to
   * @param laddr The local address to connect to
   * @param lport The local port to connect to
   * @param stream true for a stream socket, false for a datagram socket
   *
   * @exception IOException If an error occurs
277 278
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
279 280 281 282 283
   */
  private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport,
                 boolean stream) throws IOException
  {
    this();
284

285 286 287
    if (raddr == null)
      throw new NullPointerException ();
    
288 289 290 291 292 293 294
    if (impl == null)
      throw new IOException("Cannot initialize Socket implementation");

    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkConnect(raddr.getHostName(), rport);

295 296 297 298 299 300
    // bind socket
    SocketAddress bindaddr =
      laddr == null ? null : new InetSocketAddress (laddr, lport);
    bind (bindaddr);
    
    // connect socket
301
    connect (new InetSocketAddress (raddr, rport));
302

303 304 305
    // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
    // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
    // that default.  JDK 1.2 doc infers not to do a bind.
Tom Tromey committed
306 307
  }

308 309 310 311 312 313 314 315 316
  /*
   * This method may only be used by java.nio.channels.ServerSocketChannel.accept and
   * java.nio.channels.SocketChannel.open.
   */
  void setChannel (SocketChannel ch)
  {
    this.ch = ch;
  }

317
  /**
318 319 320 321
   * Binds the socket to the givent local address/port
   *
   * @param bindpoint The address/port to bind to
   *
322 323 324 325
   * @exception IOException If an error occurs
   * @exception SecurityException If a security manager exists and its
   * checkConnect method doesn't allow the operation
   * @exception IllegalArgumentException If the address type is not supported
326 327 328 329 330
   * 
   * @since 1.4
   */
  public void bind (SocketAddress bindpoint) throws IOException
  {
331 332
    if (closed)
      throw new SocketException ("Socket is closed");
333 334 335 336 337

    // XXX: JDK 1.4.1 API documentation says that if bindpoint is null the
    // socket will be bound to an ephemeral port and a valid local address.
    if (bindpoint == null)
      bindpoint = new InetSocketAddress (InetAddress.ANY_IF, 0);
338
    
339 340 341 342
    if ( !(bindpoint instanceof InetSocketAddress))
      throw new IllegalArgumentException ();

    InetSocketAddress tmp = (InetSocketAddress) bindpoint;
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    
    // create socket
    impl.create (true);
    
    // bind to address/port
    try
      {
        impl.bind (tmp.getAddress(), tmp.getPort());
      }
    catch (IOException exception)
      {
        impl.close ();
        throw exception;
      }
    catch (RuntimeException exception)
      {
        impl.close ();
        throw exception;
      }
    catch (Error error)
      {
        impl.close ();
        throw error;
      }
367 368 369 370 371 372 373 374
  }
  
  /**
   * Connects the socket with a remote address.
   *
   * @param endpoint The address to connect to
   *
   * @exception IOException If an error occurs
375
   * @exception IllegalArgumentException If the addess type is not supported
376 377
   * @exception IllegalBlockingModeException If this socket has an associated
   * channel, and the channel is in non-blocking mode
378 379 380 381 382 383
   * 
   * @since 1.4
   */
  public void connect (SocketAddress endpoint)
    throws IOException
  {
384
    connect (endpoint, 0);
385 386 387 388 389 390 391 392 393 394
  }

  /**
   * Connects the socket with a remote address. A timeout of zero is
   * interpreted as an infinite timeout. The connection will then block
   * until established or an error occurs.
   *
   * @param endpoint The address to connect to
   *
   * @exception IOException If an error occurs
395
   * @exception IllegalArgumentException If the address type is not supported
396 397
   * @exception IllegalBlockingModeException If this socket has an associated
   * channel, and the channel is in non-blocking mode
398
   * @exception SocketTimeoutException If the timeout is reached
399 400 401 402 403 404
   * 
   * @since 1.4
   */
  public void connect (SocketAddress endpoint, int timeout)
    throws IOException
  {
405 406 407
    if (closed)
      throw new SocketException ("Socket is closed");
    
408 409 410
    if (! (endpoint instanceof InetSocketAddress))
      throw new IllegalArgumentException ("Address type not supported");

411 412
    if (ch != null && !ch.isBlocking ())
      throw new IllegalBlockingModeException ();
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  
    if (!isBound ())
      bind (null);

    try
      {
        impl.connect (endpoint, timeout);
      }
    catch (IOException exception)
      {
        impl.close ();
        throw exception;
      }
    catch (RuntimeException exception)
      {
        impl.close ();
        throw exception;
      }
    catch (Error error)
      {
        impl.close ();
        throw error;
      }
436 437 438
  }

  /**
439 440 441 442 443
   * Returns the address of the remote end of the socket.  If this socket
   * is not connected, then <code>null</code> is returned.
   *
   * @return The remote address this socket is connected to
   */
Tom Tromey committed
444 445
  public InetAddress getInetAddress ()
  {
446 447 448 449
    if (impl != null)
      return impl.getInetAddress();

    return null;
Tom Tromey committed
450 451
  }

452 453 454 455 456
  /**
   * Returns the local address to which this socket is bound.  If this socket
   * is not connected, then <code>null</code> is returned.
   *
   * @return The local address
457 458
   *
   * @since 1.1
459
   */
Tom Tromey committed
460 461
  public InetAddress getLocalAddress ()
  {
462 463 464 465
    if (impl == null)
      return null;

    InetAddress addr = null;
Warren Levy committed
466 467
    try
      {
468
        addr = (InetAddress)impl.getOption(SocketOptions.SO_BINDADDR);
Warren Levy committed
469
      }
470
    catch(SocketException e)
Warren Levy committed
471
      {
472 473 474 475
        // (hopefully) shouldn't happen
        // throw new java.lang.InternalError
        //      ("Error in PlainSocketImpl.getOption");
        return null;
Warren Levy committed
476
      }
477 478 479 480 481 482 483 484 485 486 487

    // FIXME: According to libgcj, checkConnect() is supposed to be called
    // before performing this operation.  Problems: 1) We don't have the
    // addr until after we do it, so we do a post check.  2). The docs I
    // see don't require this in the Socket case, only DatagramSocket, but
    // we'll assume they mean both.
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkConnect(addr.getHostName(), getLocalPort());

    return addr;
Tom Tromey committed
488 489
  }

490 491 492 493 494 495
  /**
   * Returns the port number of the remote end of the socket connection.  If
   * this socket is not connected, then -1 is returned.
   *
   * @return The remote port this socket is connected to
   */
Tom Tromey committed
496 497
  public int getPort ()
  {
498 499 500 501
    if (impl != null)
      return impl.getPort();

    return -1;
Tom Tromey committed
502 503
  }

504 505 506 507 508 509
  /**
   * Returns the local port number to which this socket is bound.  If this
   * socket is not connected, then -1 is returned.
   *
   * @return The local port
   */
Tom Tromey committed
510 511
  public int getLocalPort ()
  {
512 513 514 515
    if (impl != null)
      return impl.getLocalPort();

    return -1;
Tom Tromey committed
516 517
  }

518
  /**
519 520 521 522 523 524 525
   * If the socket is already bound this returns the local SocketAddress,
   * otherwise null
   *
   * @since 1.4
   */
  public SocketAddress getLocalSocketAddress()
  {
526
    InetAddress addr = getLocalAddress ();
527

528 529
    if (addr == null)
      return null;
530 531 532 533 534 535 536 537 538 539 540 541
    
    return new InetSocketAddress (addr, impl.getLocalPort());
  }

  /**
   * If the socket is already connected this returns the remote SocketAddress,
   * otherwise null
   *
   * @since 1.4
   */
  public SocketAddress getRemoteSocketAddress()
  {
542 543 544
    if (!isConnected ())
      return null;

545
    return new InetSocketAddress (impl.getInetAddress (), impl.getPort ());
546 547 548
  }

  /**
549 550 551 552 553 554
   * Returns an InputStream for reading from this socket.
   *
   * @return The InputStream object
   *
   * @exception IOException If an error occurs or Socket is not connected
   */
Tom Tromey committed
555 556
  public InputStream getInputStream () throws IOException
  {
557 558 559 560
    if (impl != null)
      return(impl.getInputStream());

    throw new IOException("Not connected");
Tom Tromey committed
561 562
  }

563 564 565 566 567 568 569
  /**
   * Returns an OutputStream for writing to this socket.
   *
   * @return The OutputStream object
   *
   * @exception IOException If an error occurs or Socket is not connected
   */
Tom Tromey committed
570 571
  public OutputStream getOutputStream () throws IOException
  {
572 573 574 575
    if (impl != null)
      return impl.getOutputStream();

    throw new IOException("Not connected");
Tom Tromey committed
576 577
  }

578 579 580 581 582 583
  /**
   * Sets the TCP_NODELAY option on the socket. 
   *
   * @param on true to enable, false to disable
   * 
   * @exception SocketException If an error occurs or Socket is not connected
584 585
   *
   * @since 1.1
586
   */
Tom Tromey committed
587 588
  public void setTcpNoDelay (boolean on)  throws SocketException
  {
589 590 591 592
    if (impl == null)
      throw new SocketException("Not connected");

    impl.setOption(SocketOptions.TCP_NODELAY, new Boolean(on));
Tom Tromey committed
593 594
  }

595 596 597 598 599 600 601 602 603
  /**
   * Tests whether or not the TCP_NODELAY option is set on the socket. 
   * Returns true if enabled, false if disabled. When on it disables the
   * Nagle algorithm which means that packets are always send immediatly and
   * never merged together to reduce network trafic.
   *
   * @return Whether or not TCP_NODELAY is set
   * 
   * @exception SocketException If an error occurs or Socket not connected
604 605
   *
   * @since 1.1
606
   */
Tom Tromey committed
607 608
  public boolean getTcpNoDelay() throws SocketException
  {
609 610 611 612 613 614 615 616 617
    if (impl == null)
      throw new SocketException("Not connected");

    Object on = impl.getOption(SocketOptions.TCP_NODELAY);
  
    if (on instanceof Boolean)
      return(((Boolean)on).booleanValue());
    else
      throw new SocketException("Internal Error");
Tom Tromey committed
618 619
  }

620 621 622 623 624 625 626 627 628 629 630 631 632
  /**
   * Sets the value of the SO_LINGER option on the socket.  If the 
   * SO_LINGER option is set on a socket and there is still data waiting to
   * be sent when the socket is closed, then the close operation will block
   * until either that data is delivered or until the timeout period
   * expires.  The linger interval is specified in hundreths of a second
   * (platform specific?)
   *
   * @param on true to enable SO_LINGER, false to disable
   * @param linger The SO_LINGER timeout in hundreths of a second or -1 if 
   * SO_LINGER not set.
   *
   * @exception SocketException If an error occurs or Socket not connected
633
   * @exception IllegalArgumentException If linger is negative
634 635
   *
   * @since 1.1
636
   */
Tom Tromey committed
637 638
  public void setSoLinger(boolean on, int linger) throws SocketException
  {
639 640 641 642
    if (impl == null)
      throw new SocketException("No socket created");

    if (on == true)
Warren Levy committed
643
      {
644 645 646 647 648 649 650 651
        if (linger < 0)
          throw new IllegalArgumentException("SO_LINGER must be >= 0");

        if (linger > 65535)
          linger = 65535;

        impl.setOption(SocketOptions.SO_LINGER, new Integer(linger));
      }
Warren Levy committed
652
    else
653 654 655
      {
        impl.setOption(SocketOptions.SO_LINGER, new Boolean(false));
      }
Tom Tromey committed
656 657
  }

658 659 660 661 662 663 664 665 666 667 668 669 670
  /**
   * Returns the value of the SO_LINGER option on the socket.  If the 
   * SO_LINGER option is set on a socket and there is still data waiting to
   * be sent when the socket is closed, then the close operation will block
   * until either that data is delivered or until the timeout period
   * expires.  This method either returns the timeouts (in hundredths of
   * of a second (platform specific?)) if SO_LINGER is set, or -1 if
   * SO_LINGER is not set.
   *
   * @return The SO_LINGER timeout in hundreths of a second or -1 
   * if SO_LINGER not set
   *
   * @exception SocketException If an error occurs or Socket is not connected
671 672
   *
   * @since 1.1
673
   */
674
  public int getSoLinger() throws SocketException
Tom Tromey committed
675
  {
676 677 678 679 680 681
    if (impl == null)
      throw new SocketException("Not connected");

    Object linger = impl.getOption(SocketOptions.SO_LINGER);
    if (linger instanceof Integer)
      return(((Integer)linger).intValue());
Warren Levy committed
682 683
    else
      return -1;
Tom Tromey committed
684 685
  }

686
  /**
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
   * Sends urgent data through the socket
   *
   * @param data The data to send.
   * Only the lowest eight bits of data are sent
   *
   * @exception IOException If an error occurs
   *
   * @since 1.4
   */
  public void sendUrgentData (int data) throws IOException
  {
    impl.sendUrgentData (data);
  }

  /**
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
   * Enables/disables the SO_OOBINLINE option
   * 
   * @param on True if SO_OOBLINE should be enabled 
   * 
   * @exception SocketException If an error occurs
   * 
   * @since 1.4
   */
  public void setOOBInline (boolean on) throws SocketException
  {
    if (impl == null)
      throw new SocketException("Not connected");

    impl.setOption(SocketOptions.SO_OOBINLINE, new Boolean(on));
  }

  /**
   * Returns the current setting of the SO_OOBINLINE option for this socket
   * 
   * @exception SocketException If an error occurs
   * 
   * @since 1.4
   */
  public boolean getOOBInline () throws SocketException
  {
    if (impl == null)
      throw new SocketException("Not connected");

    Object buf = impl.getOption(SocketOptions.SO_OOBINLINE);

    if (buf instanceof Boolean)
      return(((Boolean)buf).booleanValue());
    else
      throw new SocketException("Internal Error: Unexpected type");
  }
  
  /**
739 740 741 742 743 744 745
   * Sets the value of the SO_TIMEOUT option on the socket.  If this value
   * is set, and an read/write is performed that does not complete within
   * the timeout period, a short count is returned (or an EWOULDBLOCK signal
   * would be sent in Unix if no data had been read).  A value of 0 for
   * this option implies that there is no timeout (ie, operations will 
   * block forever).  On systems that have separate read and write timeout
   * values, this method returns the read timeout.  This
746
   * value is in milliseconds.
747
   *
748 749
   * @param timeout The length of the timeout in milliseconds, or 
   * 0 to indicate no timeout.
750 751
   *
   * @exception SocketException If an error occurs or Socket not connected
752 753
   *
   * @since 1.1
754
   */
Warren Levy committed
755
  public synchronized void setSoTimeout (int timeout) throws SocketException
Tom Tromey committed
756
  {
757 758 759
    if (impl == null)
      throw new SocketException("Not connected");
    
Warren Levy committed
760
    if (timeout < 0)
761 762
      throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
      
Warren Levy committed
763
    impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
Tom Tromey committed
764 765
  }

766 767 768 769 770 771 772 773 774 775 776 777 778 779
  /**
   * Returns the value of the SO_TIMEOUT option on the socket.  If this value
   * is set, and an read/write is performed that does not complete within
   * the timeout period, a short count is returned (or an EWOULDBLOCK signal
   * would be sent in Unix if no data had been read).  A value of 0 for
   * this option implies that there is no timeout (ie, operations will 
   * block forever).  On systems that have separate read and write timeout
   * values, this method returns the read timeout.  This
   * value is in thousandths of a second (implementation specific?).
   *
   * @return The length of the timeout in thousandth's of a second or 0 
   * if not set
   *
   * @exception SocketException If an error occurs or Socket not connected
780 781
   *
   * @since 1.1
782
   */
Warren Levy committed
783
  public synchronized int getSoTimeout () throws SocketException
Tom Tromey committed
784
  {
785 786 787
    if (impl == null) 
      throw new SocketException("Not connected");

Warren Levy committed
788
    Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);
789 790
    if (timeout instanceof Integer)
      return(((Integer)timeout).intValue());
Warren Levy committed
791 792
    else
      return 0;
Tom Tromey committed
793 794
  }

795 796 797 798 799 800 801 802
  /**
   * This method sets the value for the system level socket option
   * SO_SNDBUF to the specified value.  Note that valid values for this
   * option are specific to a given operating system.
   *
   * @param size The new send buffer size.
   *
   * @exception SocketException If an error occurs or Socket not connected
803
   * @exception IllegalArgumentException If size is 0 or negative
804
   *
805
   * @since 1.2
806
   */
Tom Tromey committed
807 808
  public void setSendBufferSize (int size) throws SocketException
  {
809 810 811
    if (impl == null)
      throw new SocketException("Not connected");
    
Warren Levy committed
812
    if (size <= 0)
813 814
      throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
    
Warren Levy committed
815
    impl.setOption(SocketOptions.SO_SNDBUF, new Integer(size));
Tom Tromey committed
816 817
  }

818 819 820 821 822 823 824 825 826
  /**
   * This method returns the value of the system level socket option
   * SO_SNDBUF, which is used by the operating system to tune buffer
   * sizes for data transfers.
   *
   * @return The send buffer size.
   *
   * @exception SocketException If an error occurs or socket not connected
   *
827
   * @since 1.2
828
   */
Tom Tromey committed
829 830
  public int getSendBufferSize () throws SocketException
  {
831 832 833 834 835 836 837 838 839
    if (impl == null)
      throw new SocketException("Not connected");

    Object buf = impl.getOption(SocketOptions.SO_SNDBUF);

    if (buf instanceof Integer)
      return(((Integer)buf).intValue());
    else
      throw new SocketException("Internal Error: Unexpected type");
Tom Tromey committed
840 841
  }

842 843 844 845 846 847 848 849
  /**
   * This method sets the value for the system level socket option
   * SO_RCVBUF to the specified value.  Note that valid values for this
   * option are specific to a given operating system.
   *
   * @param size The new receive buffer size.
   *
   * @exception SocketException If an error occurs or Socket is not connected
850
   * @exception IllegalArgumentException If size is 0 or negative
851
   *
852
   * @since 1.2
853
   */
Tom Tromey committed
854 855
  public void setReceiveBufferSize (int size) throws SocketException
  {
856 857
    if (impl == null)
      throw new SocketException("Not connected");
Warren Levy committed
858

859 860 861
    if (size <= 0)
      throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
      
Warren Levy committed
862
    impl.setOption(SocketOptions.SO_RCVBUF, new Integer(size));
Tom Tromey committed
863 864
  }

865 866 867 868 869 870 871 872 873
  /**
   * This method returns the value of the system level socket option
   * SO_RCVBUF, which is used by the operating system to tune buffer
   * sizes for data transfers.
   *
   * @return The receive buffer size.
   *
   * @exception SocketException If an error occurs or Socket is not connected
   *
874
   * @since 1.2
875
   */
Tom Tromey committed
876 877
  public int getReceiveBufferSize () throws SocketException
  {
878 879 880 881 882 883 884 885 886
    if (impl == null)
      throw new SocketException("Not connected");

    Object buf = impl.getOption(SocketOptions.SO_RCVBUF);

    if (buf instanceof Integer)
      return(((Integer)buf).intValue());
    else
      throw new SocketException("Internal Error: Unexpected type");
Tom Tromey committed
887 888
  }

889
  /**
890 891 892 893 894 895 896
   * This method sets the value for the socket level socket option
   * SO_KEEPALIVE.
   *
   * @param on True if SO_KEEPALIVE should be enabled
   *
   * @exception SocketException If an error occurs or Socket is not connected
   *
897
   * @since 1.3
898 899 900 901 902 903
   */
  public void setKeepAlive (boolean on) throws SocketException
  {
    if (impl == null)
      throw new SocketException("Not connected");

904
    impl.setOption(SocketOptions.SO_KEEPALIVE, new Boolean(on));
905 906 907 908 909 910 911 912 913 914
  }

  /**
   * This method returns the value of the socket level socket option
   * SO_KEEPALIVE.
   *
   * @return The setting
   *
   * @exception SocketException If an error occurs or Socket is not connected
   *
915
   * @since 1.3
916 917 918 919 920 921
   */
  public boolean getKeepAlive () throws SocketException
  {
    if (impl == null)
      throw new SocketException("Not connected");

922
    Object buf = impl.getOption(SocketOptions.SO_KEEPALIVE);
923 924 925 926 927 928 929 930

    if (buf instanceof Boolean)
      return(((Boolean)buf).booleanValue());
    else
      throw new SocketException("Internal Error: Unexpected type");
  }

  /**
931 932 933 934
   * Closes the socket.
   *
   * @exception IOException If an error occurs
   */
Warren Levy committed
935
  public synchronized void close ()  throws IOException
Tom Tromey committed
936
  {
937 938
    if (impl != null)
      impl.close();
939 940 941 942 943

    if (ch != null)
      ch.close();
    
    closed = true;
Tom Tromey committed
944 945
  }

946 947 948 949 950
  /**
   * Converts this <code>Socket</code> to a <code>String</code>.
   *
   * @return The <code>String</code> representation of this <code>Socket</code>
   */
Tom Tromey committed
951 952
  public String toString ()
  {
953
    return("Socket " + impl);
Tom Tromey committed
954 955
  }

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
  // Class Methods

  /**
   * Sets the <code>SocketImplFactory</code>.  This may be done only once per 
   * virtual machine.  Subsequent attempts will generate a 
   * <code>SocketException</code>.  Note that a <code>SecurityManager</code>
   * check is made prior to setting the factory.  If 
   * insufficient privileges exist to set the factory, then an 
   * <code>IOException</code> will be thrown.
   *
   * @exception SecurityException If the <code>SecurityManager</code> does
   * not allow this operation.
   * @exception SocketException If the SocketImplFactory is already defined
   * @exception IOException If any other error occurs
   */
Warren Levy committed
971
  public static synchronized void setSocketImplFactory (SocketImplFactory fac)
Tom Tromey committed
972 973
    throws IOException
  {
974 975 976 977 978 979 980 981 982
    // See if already set
    if (factory != null)
      throw new SocketException("SocketImplFactory already defined");

    // Check permissions
    SecurityManager sm = System.getSecurityManager();
    if (sm != null)
      sm.checkSetFactory();

983 984 985
    if (fac == null)
      throw new SocketException("SocketImplFactory cannot be null");

Tom Tromey committed
986 987
    factory = fac;
  }
988 989 990 991 992

  /**
   * Closes the input side of the socket stream.
   *
   * @exception IOException If an error occurs.
993 994
   *
   * @since 1.3
995
   */
996
  public void shutdownInput() throws IOException
997 998 999
  {
    if (impl != null)
      impl.shutdownInput();
1000 1001

    inputShutdown = true;
1002 1003 1004 1005 1006 1007
  }

  /**
   * Closes the output side of the socket stream.
   *
   * @exception IOException If an error occurs.
1008 1009
   *
   * @since 1.3
1010 1011 1012 1013 1014
   */
  public void shutdownOutput() throws IOException
  {
    if (impl != null)
      impl.shutdownOutput();
1015 1016
    
    outputShutdown = true;
1017
  }
1018 1019 1020 1021 1022

  /**
   * Returns the socket channel associated with this socket.
   *
   * It returns null if no associated socket exists.
1023 1024
   *
   * @since 1.4
1025 1026 1027 1028 1029
   */
  public SocketChannel getChannel()
  {
    return ch;
  }
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

  /**
   * Checks if the SO_REUSEADDR option is enabled
   *
   * @exception SocketException If an error occurs
   *
   * @since 1.4
   */
  public boolean getReuseAddress () throws SocketException
  {
    if (impl == null)
      throw new SocketException ("Cannot initialize Socket implementation");

    Object reuseaddr = impl.getOption (SocketOptions.SO_REUSEADDR);

    if (!(reuseaddr instanceof Boolean))
      throw new SocketException ("Internal Error");

    return ((Boolean) reuseaddr).booleanValue ();
  }

  /**
   * Enables/Disables the SO_REUSEADDR option
   *
   * @exception SocketException If an error occurs
   *
   * @since 1.4
   */
  public void setReuseAddress (boolean on) throws SocketException
  {
    if (impl == null)
      throw new SocketException ("Cannot initialize Socket implementation");

    impl.setOption (SocketOptions.SO_REUSEADDR, new Boolean (on));
  }

  /**
   * Returns the current traffic class
   *
   * @exception SocketException If an error occurs
   *
1071
   * @see Socket#setTrafficClass(int tc)
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
   *
   * @since 1.4
   */
  public int getTrafficClass () throws SocketException
  {
    if (impl == null)
      throw new SocketException ("Cannot initialize Socket implementation");

    Object obj = impl.getOption(SocketOptions.IP_TOS);

    if (obj instanceof Integer)
      return ((Integer) obj).intValue ();
    else
      throw new SocketException ("Unexpected type");
  }

  /**
   * Sets the traffic class value
   *
   * @param tc The traffic class
   *
   * @exception SocketException If an error occurs
   * @exception IllegalArgumentException If tc value is illegal
   *
1096
   * @see Socket#getTrafficClass()
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
   *
   * @since 1.4
   */
  public void setTrafficClass (int tc) throws SocketException
  {
    if (impl == null)
      throw new SocketException ("Cannot initialize Socket implementation");

    if (tc < 0 || tc > 255)
      throw new IllegalArgumentException();

    impl.setOption (SocketOptions.IP_TOS, new Integer (tc));
  }
1110 1111

  /**
1112
   * Checks if the socket is connected
1113 1114
   *
   * @since 1.4
1115 1116 1117 1118 1119 1120 1121
   */
  public boolean isConnected ()
  {
    return impl.getInetAddress () != null;
  }

  /**
1122
   * Checks if the socket is already bound.
1123 1124
   *
   * @since 1.4
1125 1126 1127 1128 1129
   */
  public boolean isBound ()
  {
    return getLocalAddress () != null;
  }
1130 1131 1132

  /**
   * Checks if the socket is closed.
1133 1134
   * 
   * @since 1.4
1135 1136 1137
   */
  public boolean isClosed ()
  {
1138
    return closed;
1139 1140 1141 1142
  }

  /**
   * Checks if the socket's input stream is shutdown
1143 1144
   *
   * @since 1.4
1145 1146 1147 1148 1149 1150 1151 1152
   */
  public boolean isInputShutdown ()
  {
    return inputShutdown;
  }

  /**
   * Checks if the socket's output stream is shutdown
1153 1154
   *
   * @since 1.4
1155 1156 1157 1158 1159
   */
  public boolean isOutputShutdown ()
  {
    return outputShutdown;
  }
Tom Tromey committed
1160
}