1 /* Socket.java -- Client socket implementation
2 Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
41 import java
.nio
.channels
.SocketChannel
;
42 import java
.nio
.channels
.IllegalBlockingModeException
;
44 /* Written using on-line Java Platform 1.2 API Specification.
45 * Status: I believe all methods are implemented.
49 * This class models a client site socket. A socket is a TCP/IP endpoint
50 * for network communications conceptually similar to a file handle.
52 * This class does not actually do any work. Instead, it redirects all of
53 * its calls to a socket implementation object which implements the
54 * <code>SocketImpl</code> interface. The implementation class is
55 * instantiated by factory class that implements the
56 * <code>SocketImplFactory interface</code>. A default
57 * factory is provided, however the factory may be set by a call to
58 * the <code>setSocketImplFactory</code> method. Note that this may only be
59 * done once per virtual machine. If a subsequent attempt is made to set the
60 * factory, a <code>SocketException</code> will be thrown.
62 * @author Aaron M. Renn (arenn@urbanophile.com)
63 * @author Per Bothner (bothner@cygnus.com)
71 * This is the user SocketImplFactory for this class. If this variable is
72 * null, a default factory is used.
74 static SocketImplFactory factory
;
79 * The implementation object to which calls are redirected
83 SocketChannel ch
; // this field must have been set if created by SocketChannel
88 * Initializes a new instance of <code>Socket</code> object without
89 * connecting to a remote host. This useful for subclasses of socket that
90 * might want this behavior.
92 * @specnote This constructor is public since JDK 1.4
97 impl
= factory
.createSocketImpl();
99 impl
= new PlainSocketImpl();
103 * Initializes a new instance of <code>Socket</code> object without
104 * connecting to a remote host. This is useful for subclasses of socket
105 * that might want this behavior.
107 * Additionally, this socket will be created using the supplied
108 * implementation class instead the default class or one returned by a
109 * factory. This value can be <code>null</code>, but if it is, all instance
110 * methods in <code>Socket</code> should be overridden because most of them
111 * rely on this value being populated.
113 * @param impl The <code>SocketImpl</code> to use for this
114 * <code>Socket</code>
116 * @exception SocketException If an error occurs
118 protected Socket (SocketImpl impl
) throws SocketException
124 * Initializes a new instance of <code>Socket</code> and connects to the
125 * hostname and port specified as arguments.
127 * @param host The name of the host to connect to
128 * @param port The port number to connect to
130 * @exception UnknownHostException If the hostname cannot be resolved to a
132 * @exception IOException If an error occurs
133 * @exception SecurityException If a security manager exists and its
134 * checkConnect method doesn't allow the operation
136 public Socket (String host
, int port
)
137 throws UnknownHostException
, IOException
139 this(InetAddress
.getByName(host
), port
, null, 0, true);
143 * Initializes a new instance of <code>Socket</code> and connects to the
144 * address and port number specified as arguments.
146 * @param address The address to connect to
147 * @param port The port number to connect to
149 * @exception IOException If an error occurs
150 * @exception SecurityException If a security manager exists and its
151 * checkConnect method doesn't allow the operation
153 public Socket (InetAddress address
, int port
)
156 this(address
, port
, null, 0, true);
160 * Initializes a new instance of <code>Socket</code> that connects to the
161 * named host on the specified port and binds to the specified local address
164 * @param host The name of the remote host to connect to.
165 * @param port The remote port to connect to.
166 * @param loadAddr The local address to bind to.
167 * @param localPort The local port to bind to.
169 * @exception SecurityException If the <code>SecurityManager</code>
170 * exists and does not allow a connection to the specified host/port or
171 * binding to the specified local host/port.
172 * @exception IOException If a connection error occurs.
174 public Socket (String host
, int port
,
175 InetAddress localAddr
, int localPort
) throws IOException
177 this(InetAddress
.getByName(host
), port
, localAddr
, localPort
, true);
181 * Initializes a new instance of <code>Socket</code> and connects to the
182 * address and port number specified as arguments, plus binds to the
183 * specified local address and port.
185 * @param address The remote address to connect to
186 * @param port The remote port to connect to
187 * @param localAddr The local address to connect to
188 * @param localPort The local port to connect to
190 * @exception IOException If an error occurs
191 * @exception SecurityException If a security manager exists and its
192 * checkConnect method doesn't allow the operation
194 public Socket (InetAddress address
, int port
,
195 InetAddress localAddr
, int localPort
) throws IOException
197 this(address
, port
, localAddr
, localPort
, true);
201 * Initializes a new instance of <code>Socket</code> and connects to the
202 * hostname and port specified as arguments. If the stream argument is set
203 * to <code>true</code>, then a stream socket is created. If it is
204 * <code>false</code>, a datagram socket is created.
206 * @param host The name of the host to connect to
207 * @param port The port to connect to
208 * @param stream <code>true</code> for a stream socket, <code>false</code>
209 * for a datagram socket
211 * @exception IOException If an error occurs
212 * @exception SecurityException If a security manager exists and its
213 * checkConnect method doesn't allow the operation
215 * @deprecated Use the <code>DatagramSocket</code> class to create
216 * datagram oriented sockets.
218 public Socket (String host
, int port
, boolean stream
) throws IOException
220 this(InetAddress
.getByName(host
), port
, null, 0, stream
);
224 * Initializes a new instance of <code>Socket</code> and connects to the
225 * address and port number specified as arguments. If the stream param is
226 * <code>true</code>, a stream socket will be created, otherwise a datagram
229 * @param host The address to connect to
230 * @param port The port number to connect to
231 * @param stream <code>true</code> to create a stream socket,
232 * <code>false</code> to create a datagram socket.
234 * @exception IOException If an error occurs
235 * @exception SecurityException If a security manager exists and its
236 * checkConnect method doesn't allow the operation
238 * @deprecated Use the <code>DatagramSocket</code> class to create
239 * datagram oriented sockets.
241 public Socket (InetAddress host
, int port
, boolean stream
) throws IOException
243 this(host
, port
, null, 0, stream
);
247 * This constructor is where the real work takes place. Connect to the
248 * specified address and port. Use default local values if not specified,
249 * otherwise use the local host and port passed in. Create as stream or
250 * datagram based on "stream" argument.
253 * @param raddr The remote address to connect to
254 * @param rport The remote port to connect to
255 * @param laddr The local address to connect to
256 * @param lport The local port to connect to
257 * @param stream true for a stream socket, false for a datagram socket
259 * @exception IOException If an error occurs
260 * @exception SecurityException If a security manager exists and its
261 * checkConnect method doesn't allow the operation
263 private Socket(InetAddress raddr
, int rport
, InetAddress laddr
, int lport
,
264 boolean stream
) throws IOException
268 throw new IOException("Cannot initialize Socket implementation");
270 SecurityManager sm
= System
.getSecurityManager();
272 sm
.checkConnect(raddr
.getHostName(), rport
);
276 // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
277 // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
278 // that default. JDK 1.2 doc infers not to do a bind.
280 impl
.bind(laddr
, lport
);
283 impl
.connect(raddr
, rport
);
287 * Binds the socket to the givent local address/port
289 * @param bindpoint The address/port to bind to
291 * @exception IOException If an error occurs
292 * @exception SecurityException If a security manager exists and its
293 * checkConnect method doesn't allow the operation
294 * @exception IllegalArgumentException If the address type is not supported
298 public void bind (SocketAddress bindpoint
) throws IOException
300 if ( !(bindpoint
instanceof InetSocketAddress
))
301 throw new IllegalArgumentException ();
303 InetSocketAddress tmp
= (InetSocketAddress
) bindpoint
;
304 impl
.bind (tmp
.getAddress(), tmp
.getPort());
308 * Connects the socket with a remote address.
310 * @param endpoint The address to connect to
312 * @exception IOException If an error occurs
313 * @exception IllegalArgumentException If the addess type is not supported
314 * @exception IllegalBlockingModeException If this socket has an associated
315 * channel, and the channel is in non-blocking mode
319 public void connect (SocketAddress endpoint
)
322 if (! (endpoint
instanceof InetSocketAddress
))
323 throw new IllegalArgumentException ("Address type not supported");
325 if (ch
!= null && !ch
.isBlocking ())
326 throw new IllegalBlockingModeException ();
328 impl
.connect (endpoint
, 0);
332 * Connects the socket with a remote address. A timeout of zero is
333 * interpreted as an infinite timeout. The connection will then block
334 * until established or an error occurs.
336 * @param endpoint The address to connect to
338 * @exception IOException If an error occurs
339 * @exception IllegalArgumentException If the address type is not supported
340 * @exception IllegalBlockingModeException If this socket has an associated
341 * channel, and the channel is in non-blocking mode
342 * @exception SocketTimeoutException If the timeout is reached
346 public void connect (SocketAddress endpoint
, int timeout
)
349 if (! (endpoint
instanceof InetSocketAddress
))
350 throw new IllegalArgumentException ("Address type not supported");
352 if (ch
!= null && !ch
.isBlocking ())
353 throw new IllegalBlockingModeException ();
355 impl
.connect (endpoint
, timeout
);
359 * Returns the address of the remote end of the socket. If this socket
360 * is not connected, then <code>null</code> is returned.
362 * @return The remote address this socket is connected to
364 public InetAddress
getInetAddress ()
367 return impl
.getInetAddress();
373 * Returns the local address to which this socket is bound. If this socket
374 * is not connected, then <code>null</code> is returned.
376 * @return The local address
378 public InetAddress
getLocalAddress ()
383 InetAddress addr
= null;
386 addr
= (InetAddress
)impl
.getOption(SocketOptions
.SO_BINDADDR
);
388 catch(SocketException e
)
390 // (hopefully) shouldn't happen
391 // throw new java.lang.InternalError
392 // ("Error in PlainSocketImpl.getOption");
396 // FIXME: According to libgcj, checkConnect() is supposed to be called
397 // before performing this operation. Problems: 1) We don't have the
398 // addr until after we do it, so we do a post check. 2). The docs I
399 // see don't require this in the Socket case, only DatagramSocket, but
400 // we'll assume they mean both.
401 SecurityManager sm
= System
.getSecurityManager();
403 sm
.checkConnect(addr
.getHostName(), getLocalPort());
409 * Returns the port number of the remote end of the socket connection. If
410 * this socket is not connected, then -1 is returned.
412 * @return The remote port this socket is connected to
414 public int getPort ()
417 return impl
.getPort();
423 * Returns the local port number to which this socket is bound. If this
424 * socket is not connected, then -1 is returned.
426 * @return The local port
428 public int getLocalPort ()
431 return impl
.getLocalPort();
437 * If the socket is already bound this returns the local SocketAddress,
442 public SocketAddress
getLocalSocketAddress()
444 InetAddress addr
= getLocalAddress ();
449 return new InetSocketAddress (addr
, impl
.getLocalPort());
453 * If the socket is already connected this returns the remote SocketAddress,
458 public SocketAddress
getRemoteSocketAddress()
460 return new InetSocketAddress (impl
.getInetAddress (), impl
.getPort ());
464 * Returns an InputStream for reading from this socket.
466 * @return The InputStream object
468 * @exception IOException If an error occurs or Socket is not connected
470 public InputStream
getInputStream () throws IOException
473 return(impl
.getInputStream());
475 throw new IOException("Not connected");
479 * Returns an OutputStream for writing to this socket.
481 * @return The OutputStream object
483 * @exception IOException If an error occurs or Socket is not connected
485 public OutputStream
getOutputStream () throws IOException
488 return impl
.getOutputStream();
490 throw new IOException("Not connected");
494 * Sets the TCP_NODELAY option on the socket.
496 * @param on true to enable, false to disable
498 * @exception SocketException If an error occurs or Socket is not connected
500 public void setTcpNoDelay (boolean on
) throws SocketException
503 throw new SocketException("Not connected");
505 impl
.setOption(SocketOptions
.TCP_NODELAY
, new Boolean(on
));
509 * Tests whether or not the TCP_NODELAY option is set on the socket.
510 * Returns true if enabled, false if disabled. When on it disables the
511 * Nagle algorithm which means that packets are always send immediatly and
512 * never merged together to reduce network trafic.
514 * @return Whether or not TCP_NODELAY is set
516 * @exception SocketException If an error occurs or Socket not connected
518 public boolean getTcpNoDelay() throws SocketException
521 throw new SocketException("Not connected");
523 Object on
= impl
.getOption(SocketOptions
.TCP_NODELAY
);
525 if (on
instanceof Boolean
)
526 return(((Boolean
)on
).booleanValue());
528 throw new SocketException("Internal Error");
532 * Sets the value of the SO_LINGER option on the socket. If the
533 * SO_LINGER option is set on a socket and there is still data waiting to
534 * be sent when the socket is closed, then the close operation will block
535 * until either that data is delivered or until the timeout period
536 * expires. The linger interval is specified in hundreths of a second
537 * (platform specific?)
539 * @param on true to enable SO_LINGER, false to disable
540 * @param linger The SO_LINGER timeout in hundreths of a second or -1 if
543 * @exception SocketException If an error occurs or Socket not connected
544 * @exception IllegalArgumentException If linger is negative
546 public void setSoLinger(boolean on
, int linger
) throws SocketException
549 throw new SocketException("No socket created");
554 throw new IllegalArgumentException("SO_LINGER must be >= 0");
559 impl
.setOption(SocketOptions
.SO_LINGER
, new Integer(linger
));
563 impl
.setOption(SocketOptions
.SO_LINGER
, new Boolean(false));
568 * Returns the value of the SO_LINGER option on the socket. If the
569 * SO_LINGER option is set on a socket and there is still data waiting to
570 * be sent when the socket is closed, then the close operation will block
571 * until either that data is delivered or until the timeout period
572 * expires. This method either returns the timeouts (in hundredths of
573 * of a second (platform specific?)) if SO_LINGER is set, or -1 if
574 * SO_LINGER is not set.
576 * @return The SO_LINGER timeout in hundreths of a second or -1
577 * if SO_LINGER not set
579 * @exception SocketException If an error occurs or Socket is not connected
581 public int getSoLinger() throws SocketException
584 throw new SocketException("Not connected");
586 Object linger
= impl
.getOption(SocketOptions
.SO_LINGER
);
587 if (linger
instanceof Integer
)
588 return(((Integer
)linger
).intValue());
594 * Sends urgent data through the socket
596 * @param data The data to send.
597 * Only the lowest eight bits of data are sent
599 * @exception IOException If an error occurs
603 public void sendUrgentData (int data
) throws IOException
605 impl
.sendUrgentData (data
);
609 * Enables/disables the SO_OOBINLINE option
611 * @param on True if SO_OOBLINE should be enabled
613 * @exception SocketException If an error occurs
617 public void setOOBInline (boolean on
) throws SocketException
620 throw new SocketException("Not connected");
622 impl
.setOption(SocketOptions
.SO_OOBINLINE
, new Boolean(on
));
626 * Returns the current setting of the SO_OOBINLINE option for this socket
628 * @exception SocketException If an error occurs
632 public boolean getOOBInline () throws SocketException
635 throw new SocketException("Not connected");
637 Object buf
= impl
.getOption(SocketOptions
.SO_OOBINLINE
);
639 if (buf
instanceof Boolean
)
640 return(((Boolean
)buf
).booleanValue());
642 throw new SocketException("Internal Error: Unexpected type");
646 * Sets the value of the SO_TIMEOUT option on the socket. If this value
647 * is set, and an read/write is performed that does not complete within
648 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
649 * would be sent in Unix if no data had been read). A value of 0 for
650 * this option implies that there is no timeout (ie, operations will
651 * block forever). On systems that have separate read and write timeout
652 * values, this method returns the read timeout. This
653 * value is in thousandths of a second (****????*****)
655 * @param timeout The length of the timeout in thousandth's of a second or
658 * @exception SocketException If an error occurs or Socket not connected
660 public synchronized void setSoTimeout (int timeout
) throws SocketException
663 throw new SocketException("Not connected");
666 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
668 impl
.setOption(SocketOptions
.SO_TIMEOUT
, new Integer(timeout
));
672 * Returns the value of the SO_TIMEOUT option on the socket. If this value
673 * is set, and an read/write is performed that does not complete within
674 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
675 * would be sent in Unix if no data had been read). A value of 0 for
676 * this option implies that there is no timeout (ie, operations will
677 * block forever). On systems that have separate read and write timeout
678 * values, this method returns the read timeout. This
679 * value is in thousandths of a second (implementation specific?).
681 * @return The length of the timeout in thousandth's of a second or 0
684 * @exception SocketException If an error occurs or Socket not connected
686 public synchronized int getSoTimeout () throws SocketException
689 throw new SocketException("Not connected");
691 Object timeout
= impl
.getOption(SocketOptions
.SO_TIMEOUT
);
692 if (timeout
instanceof Integer
)
693 return(((Integer
)timeout
).intValue());
699 * This method sets the value for the system level socket option
700 * SO_SNDBUF to the specified value. Note that valid values for this
701 * option are specific to a given operating system.
703 * @param size The new send buffer size.
705 * @exception SocketException If an error occurs or Socket not connected
706 * @exception IllegalArgumentException If size is 0 or negative
710 public void setSendBufferSize (int size
) throws SocketException
713 throw new SocketException("Not connected");
716 throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
718 impl
.setOption(SocketOptions
.SO_SNDBUF
, new Integer(size
));
722 * This method returns the value of the system level socket option
723 * SO_SNDBUF, which is used by the operating system to tune buffer
724 * sizes for data transfers.
726 * @return The send buffer size.
728 * @exception SocketException If an error occurs or socket not connected
732 public int getSendBufferSize () throws SocketException
735 throw new SocketException("Not connected");
737 Object buf
= impl
.getOption(SocketOptions
.SO_SNDBUF
);
739 if (buf
instanceof Integer
)
740 return(((Integer
)buf
).intValue());
742 throw new SocketException("Internal Error: Unexpected type");
746 * This method sets the value for the system level socket option
747 * SO_RCVBUF to the specified value. Note that valid values for this
748 * option are specific to a given operating system.
750 * @param size The new receive buffer size.
752 * @exception SocketException If an error occurs or Socket is not connected
753 * @exception IllegalArgumentException If size is 0 or negative
757 public void setReceiveBufferSize (int size
) throws SocketException
760 throw new SocketException("Not connected");
763 throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
765 impl
.setOption(SocketOptions
.SO_RCVBUF
, new Integer(size
));
769 * This method returns the value of the system level socket option
770 * SO_RCVBUF, which is used by the operating system to tune buffer
771 * sizes for data transfers.
773 * @return The receive buffer size.
775 * @exception SocketException If an error occurs or Socket is not connected
779 public int getReceiveBufferSize () throws SocketException
782 throw new SocketException("Not connected");
784 Object buf
= impl
.getOption(SocketOptions
.SO_RCVBUF
);
786 if (buf
instanceof Integer
)
787 return(((Integer
)buf
).intValue());
789 throw new SocketException("Internal Error: Unexpected type");
793 * This method sets the value for the socket level socket option
796 * @param on True if SO_KEEPALIVE should be enabled
798 * @exception SocketException If an error occurs or Socket is not connected
802 public void setKeepAlive (boolean on
) throws SocketException
805 throw new SocketException("Not connected");
807 impl
.setOption(SocketOptions
.SO_KEEPALIVE
, new Boolean(on
));
811 * This method returns the value of the socket level socket option
814 * @return The setting
816 * @exception SocketException If an error occurs or Socket is not connected
820 public boolean getKeepAlive () throws SocketException
823 throw new SocketException("Not connected");
825 Object buf
= impl
.getOption(SocketOptions
.SO_KEEPALIVE
);
827 if (buf
instanceof Boolean
)
828 return(((Boolean
)buf
).booleanValue());
830 throw new SocketException("Internal Error: Unexpected type");
836 * @exception IOException If an error occurs
838 public synchronized void close () throws IOException
845 * Converts this <code>Socket</code> to a <code>String</code>.
847 * @return The <code>String</code> representation of this <code>Socket</code>
849 public String
toString ()
851 return("Socket " + impl
);
857 * Sets the <code>SocketImplFactory</code>. This may be done only once per
858 * virtual machine. Subsequent attempts will generate a
859 * <code>SocketException</code>. Note that a <code>SecurityManager</code>
860 * check is made prior to setting the factory. If
861 * insufficient privileges exist to set the factory, then an
862 * <code>IOException</code> will be thrown.
864 * @exception SecurityException If the <code>SecurityManager</code> does
865 * not allow this operation.
866 * @exception SocketException If the SocketImplFactory is already defined
867 * @exception IOException If any other error occurs
869 public static synchronized void setSocketImplFactory (SocketImplFactory fac
)
872 // See if already set
874 throw new SocketException("SocketImplFactory already defined");
877 SecurityManager sm
= System
.getSecurityManager();
879 sm
.checkSetFactory();
885 * Closes the input side of the socket stream.
887 * @exception IOException If an error occurs.
889 public void shutdownInput() throws IOException
892 impl
.shutdownInput();
896 * Closes the output side of the socket stream.
898 * @exception IOException If an error occurs.
900 public void shutdownOutput() throws IOException
903 impl
.shutdownOutput();
907 * Returns the socket channel associated with this socket.
909 * It returns null if no associated socket exists.
911 public SocketChannel
getChannel()
917 * Checks if the SO_REUSEADDR option is enabled
919 * @exception SocketException If an error occurs
923 public boolean getReuseAddress () throws SocketException
926 throw new SocketException ("Cannot initialize Socket implementation");
928 Object reuseaddr
= impl
.getOption (SocketOptions
.SO_REUSEADDR
);
930 if (!(reuseaddr
instanceof Boolean
))
931 throw new SocketException ("Internal Error");
933 return ((Boolean
) reuseaddr
).booleanValue ();
937 * Enables/Disables the SO_REUSEADDR option
939 * @exception SocketException If an error occurs
943 public void setReuseAddress (boolean on
) throws SocketException
946 throw new SocketException ("Cannot initialize Socket implementation");
948 impl
.setOption (SocketOptions
.SO_REUSEADDR
, new Boolean (on
));
952 * Returns the current traffic class
954 * @exception SocketException If an error occurs
956 * @see Socket:setTrafficClass
960 public int getTrafficClass () throws SocketException
963 throw new SocketException ("Cannot initialize Socket implementation");
965 Object obj
= impl
.getOption(SocketOptions
.IP_TOS
);
967 if (obj
instanceof Integer
)
968 return ((Integer
) obj
).intValue ();
970 throw new SocketException ("Unexpected type");
974 * Sets the traffic class value
976 * @param tc The traffic class
978 * @exception SocketException If an error occurs
979 * @exception IllegalArgumentException If tc value is illegal
981 * @see Socket:getTrafficClass
985 public void setTrafficClass (int tc
) throws SocketException
988 throw new SocketException ("Cannot initialize Socket implementation");
990 if (tc
< 0 || tc
> 255)
991 throw new IllegalArgumentException();
993 impl
.setOption (SocketOptions
.IP_TOS
, new Integer (tc
));
997 * Checks if the socket is already bound.
999 public boolean isBound ()
1001 return getLocalAddress () != null;