* gnu/java/net/PlainSocketImpl.java
[gcc.git] / libjava / java / net / Socket.java
1 /* Socket.java -- Client socket implementation
2 Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Classpath.
6
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 02111-1307 USA.
21
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
26
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
38
39
40 package java.net;
41
42 import gnu.java.net.PlainSocketImpl;
43 import java.io.InputStream;
44 import java.io.IOException;
45 import java.io.OutputStream;
46 import java.nio.channels.SocketChannel;
47 import java.nio.channels.IllegalBlockingModeException;
48
49 /* Written using on-line Java Platform 1.2 API Specification.
50 * Status: I believe all methods are implemented.
51 */
52
53 /**
54 * This class models a client site socket. A socket is a TCP/IP endpoint
55 * for network communications conceptually similar to a file handle.
56 * <p>
57 * This class does not actually do any work. Instead, it redirects all of
58 * its calls to a socket implementation object which implements the
59 * <code>SocketImpl</code> interface. The implementation class is
60 * instantiated by factory class that implements the
61 * <code>SocketImplFactory interface</code>. A default
62 * factory is provided, however the factory may be set by a call to
63 * the <code>setSocketImplFactory</code> method. Note that this may only be
64 * done once per virtual machine. If a subsequent attempt is made to set the
65 * factory, a <code>SocketException</code> will be thrown.
66 *
67 * @author Aaron M. Renn (arenn@urbanophile.com)
68 * @author Per Bothner (bothner@cygnus.com)
69 */
70 public class Socket
71 {
72 /**
73 * This is the user SocketImplFactory for this class. If this variable is
74 * null, a default factory is used.
75 */
76 static SocketImplFactory factory;
77
78 /**
79 * The implementation object to which calls are redirected
80 */
81 private SocketImpl impl;
82
83 /**
84 * True if socket implementation was created by calling their create() method.
85 */
86 private boolean implCreated;
87
88 /**
89 * True if the socket is bound.
90 */
91 private boolean bound;
92
93 /**
94 * True if input is shutdown.
95 */
96 private boolean inputShutdown;
97
98 /**
99 * True if output is shutdown.
100 */
101 private boolean outputShutdown;
102
103 /**
104 * Initializes a new instance of <code>Socket</code> object without
105 * connecting to a remote host. This useful for subclasses of socket that
106 * might want this behavior.
107 *
108 * @specnote This constructor is public since JDK 1.4
109 * @since 1.1
110 */
111 public Socket ()
112 {
113 if (factory != null)
114 impl = factory.createSocketImpl();
115 else
116 impl = new PlainSocketImpl();
117 }
118
119 /**
120 * Initializes a new instance of <code>Socket</code> object without
121 * connecting to a remote host. This is useful for subclasses of socket
122 * that might want this behavior.
123 * <p>
124 * Additionally, this socket will be created using the supplied
125 * implementation class instead the default class or one returned by a
126 * factory. If this value is <code>null</code>, the default Socket
127 * implementation is used.
128 *
129 * @param impl The <code>SocketImpl</code> to use for this
130 * <code>Socket</code>
131 *
132 * @exception SocketException If an error occurs
133 *
134 * @since 1.1
135 */
136 protected Socket (SocketImpl impl) throws SocketException
137 {
138 if (impl == null)
139 this.impl = new PlainSocketImpl();
140 else
141 this.impl = impl;
142 }
143
144 /**
145 * Initializes a new instance of <code>Socket</code> and connects to the
146 * hostname and port specified as arguments.
147 *
148 * @param host The name of the host to connect to
149 * @param port The port number to connect to
150 *
151 * @exception UnknownHostException If the hostname cannot be resolved to a
152 * network address.
153 * @exception IOException If an error occurs
154 * @exception SecurityException If a security manager exists and its
155 * checkConnect method doesn't allow the operation
156 */
157 public Socket (String host, int port)
158 throws UnknownHostException, IOException
159 {
160 this(InetAddress.getByName(host), port, null, 0, true);
161 }
162
163 /**
164 * Initializes a new instance of <code>Socket</code> and connects to the
165 * address and port number specified as arguments.
166 *
167 * @param address The address to connect to
168 * @param port The port number to connect to
169 *
170 * @exception IOException If an error occurs
171 * @exception SecurityException If a security manager exists and its
172 * checkConnect method doesn't allow the operation
173 */
174 public Socket (InetAddress address, int port)
175 throws IOException
176 {
177 this(address, port, null, 0, true);
178 }
179
180 /**
181 * Initializes a new instance of <code>Socket</code> that connects to the
182 * named host on the specified port and binds to the specified local address
183 * and port.
184 *
185 * @param host The name of the remote host to connect to.
186 * @param port The remote port to connect to.
187 * @param localAddr The local address to bind to.
188 * @param localPort The local port to bind to.
189 *
190 * @exception SecurityException If the <code>SecurityManager</code>
191 * exists and does not allow a connection to the specified host/port or
192 * binding to the specified local host/port.
193 * @exception IOException If a connection error occurs.
194 *
195 * @since 1.1
196 */
197 public Socket (String host, int port,
198 InetAddress localAddr, int localPort) throws IOException
199 {
200 this(InetAddress.getByName(host), port, localAddr, localPort, true);
201 }
202
203 /**
204 * Initializes a new instance of <code>Socket</code> and connects to the
205 * address and port number specified as arguments, plus binds to the
206 * specified local address and port.
207 *
208 * @param address The remote address to connect to
209 * @param port The remote port to connect to
210 * @param localAddr The local address to connect to
211 * @param localPort The local port to connect to
212 *
213 * @exception IOException If an error occurs
214 * @exception SecurityException If a security manager exists and its
215 * checkConnect method doesn't allow the operation
216 *
217 * @since 1.1
218 */
219 public Socket (InetAddress address, int port,
220 InetAddress localAddr, int localPort) throws IOException
221 {
222 this(address, port, localAddr, localPort, true);
223 }
224
225 /**
226 * Initializes a new instance of <code>Socket</code> and connects to the
227 * hostname and port specified as arguments. If the stream argument is set
228 * to <code>true</code>, then a stream socket is created. If it is
229 * <code>false</code>, a datagram socket is created.
230 *
231 * @param host The name of the host to connect to
232 * @param port The port to connect to
233 * @param stream <code>true</code> for a stream socket, <code>false</code>
234 * for a datagram socket
235 *
236 * @exception IOException If an error occurs
237 * @exception SecurityException If a security manager exists and its
238 * checkConnect method doesn't allow the operation
239 *
240 * @deprecated Use the <code>DatagramSocket</code> class to create
241 * datagram oriented sockets.
242 */
243 public Socket (String host, int port, boolean stream) throws IOException
244 {
245 this(InetAddress.getByName(host), port, null, 0, stream);
246 }
247
248 /**
249 * Initializes a new instance of <code>Socket</code> and connects to the
250 * address and port number specified as arguments. If the stream param is
251 * <code>true</code>, a stream socket will be created, otherwise a datagram
252 * socket is created.
253 *
254 * @param host The address to connect to
255 * @param port The port number to connect to
256 * @param stream <code>true</code> to create a stream socket,
257 * <code>false</code> to create a datagram socket.
258 *
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
262 *
263 * @deprecated Use the <code>DatagramSocket</code> class to create
264 * datagram oriented sockets.
265 */
266 public Socket (InetAddress host, int port, boolean stream) throws IOException
267 {
268 this(host, port, null, 0, stream);
269 }
270
271 /**
272 * This constructor is where the real work takes place. Connect to the
273 * specified address and port. Use default local values if not specified,
274 * otherwise use the local host and port passed in. Create as stream or
275 * datagram based on "stream" argument.
276 * <p>
277 *
278 * @param raddr The remote address to connect to
279 * @param rport The remote port to connect to
280 * @param laddr The local address to connect to
281 * @param lport The local port to connect to
282 * @param stream true for a stream socket, false for a datagram socket
283 *
284 * @exception IOException If an error occurs
285 * @exception SecurityException If a security manager exists and its
286 * checkConnect method doesn't allow the operation
287 */
288 private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport,
289 boolean stream) throws IOException
290 {
291 this();
292
293 SecurityManager sm = System.getSecurityManager();
294 if (sm != null)
295 sm.checkConnect(raddr.getHostName(), rport);
296
297 // bind socket
298 SocketAddress bindaddr =
299 laddr == null ? null : new InetSocketAddress (laddr, lport);
300 bind (bindaddr);
301
302 // connect socket
303 connect (new InetSocketAddress (raddr, rport));
304
305 // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
306 // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
307 // that default. JDK 1.2 doc infers not to do a bind.
308 }
309
310 // This has to be accessible from java.net.ServerSocket.
311 SocketImpl getImpl()
312 throws SocketException
313 {
314 try
315 {
316 if (!implCreated)
317 {
318 impl.create(true);
319 implCreated = true;
320 }
321 }
322 catch (IOException e)
323 {
324 throw new SocketException(e.getMessage());
325 }
326
327 return impl;
328 }
329
330 /**
331 * Binds the socket to the givent local address/port
332 *
333 * @param bindpoint The address/port to bind to
334 *
335 * @exception IOException If an error occurs
336 * @exception SecurityException If a security manager exists and its
337 * checkConnect method doesn't allow the operation
338 * @exception IllegalArgumentException If the address type is not supported
339 *
340 * @since 1.4
341 */
342 public void bind (SocketAddress bindpoint) throws IOException
343 {
344 if (isClosed())
345 throw new SocketException("socket is closed");
346
347 // XXX: JDK 1.4.1 API documentation says that if bindpoint is null the
348 // socket will be bound to an ephemeral port and a valid local address.
349 if (bindpoint == null)
350 bindpoint = new InetSocketAddress (InetAddress.ANY_IF, 0);
351
352 if ( !(bindpoint instanceof InetSocketAddress))
353 throw new IllegalArgumentException ();
354
355 InetSocketAddress tmp = (InetSocketAddress) bindpoint;
356
357 // bind to address/port
358 try
359 {
360 getImpl().bind (tmp.getAddress(), tmp.getPort());
361 bound = true;
362 }
363 catch (IOException exception)
364 {
365 close ();
366 throw exception;
367 }
368 catch (RuntimeException exception)
369 {
370 close ();
371 throw exception;
372 }
373 catch (Error error)
374 {
375 close ();
376 throw error;
377 }
378 }
379
380 /**
381 * Connects the socket with a remote address.
382 *
383 * @param endpoint The address to connect to
384 *
385 * @exception IOException If an error occurs
386 * @exception IllegalArgumentException If the addess type is not supported
387 * @exception IllegalBlockingModeException If this socket has an associated
388 * channel, and the channel is in non-blocking mode
389 *
390 * @since 1.4
391 */
392 public void connect (SocketAddress endpoint)
393 throws IOException
394 {
395 connect (endpoint, 0);
396 }
397
398 /**
399 * Connects the socket with a remote address. A timeout of zero is
400 * interpreted as an infinite timeout. The connection will then block
401 * until established or an error occurs.
402 *
403 * @param endpoint The address to connect to
404 * @param timeout The length of the timeout in milliseconds, or
405 * 0 to indicate no timeout.
406 *
407 * @exception IOException If an error occurs
408 * @exception IllegalArgumentException If the address type is not supported
409 * @exception IllegalBlockingModeException If this socket has an associated
410 * channel, and the channel is in non-blocking mode
411 * @exception SocketTimeoutException If the timeout is reached
412 *
413 * @since 1.4
414 */
415 public void connect (SocketAddress endpoint, int timeout)
416 throws IOException
417 {
418 if (isClosed())
419 throw new SocketException("socket is closed");
420
421 if (! (endpoint instanceof InetSocketAddress))
422 throw new IllegalArgumentException("unsupported address type");
423
424 // The Sun spec says that if we have an associated channel and
425 // it is in non-blocking mode, we throw an IllegalBlockingModeException.
426 // However, in our implementation if the channel itself initiated this
427 // operation, then we must honor it regardless of its blocking mode.
428 if (getChannel() != null
429 && !getChannel().isBlocking ()
430 && !((PlainSocketImpl) getImpl()).isInChannelOperation())
431 throw new IllegalBlockingModeException ();
432
433 if (!isBound ())
434 bind (null);
435
436 try
437 {
438 getImpl().connect (endpoint, timeout);
439 }
440 catch (IOException exception)
441 {
442 close ();
443 throw exception;
444 }
445 catch (RuntimeException exception)
446 {
447 close ();
448 throw exception;
449 }
450 catch (Error error)
451 {
452 close ();
453 throw error;
454 }
455 }
456
457 /**
458 * Returns the address of the remote end of the socket. If this socket
459 * is not connected, then <code>null</code> is returned.
460 *
461 * @return The remote address this socket is connected to
462 */
463 public InetAddress getInetAddress ()
464 {
465 if (!isConnected())
466 return null;
467
468 try
469 {
470 return getImpl().getInetAddress();
471 }
472 catch (SocketException e)
473 {
474 // This cannot happen as we are connected.
475 }
476
477 return null;
478 }
479
480 /**
481 * Returns the local address to which this socket is bound. If this socket
482 * is not connected, then <code>null</code> is returned.
483 *
484 * @return The local address
485 *
486 * @since 1.1
487 */
488 public InetAddress getLocalAddress ()
489 {
490 InetAddress addr = null;
491
492 try
493 {
494 addr = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
495 }
496 catch(SocketException e)
497 {
498 // (hopefully) shouldn't happen
499 // throw new java.lang.InternalError
500 // ("Error in PlainSocketImpl.getOption");
501 return null;
502 }
503
504 // FIXME: According to libgcj, checkConnect() is supposed to be called
505 // before performing this operation. Problems: 1) We don't have the
506 // addr until after we do it, so we do a post check. 2). The docs I
507 // see don't require this in the Socket case, only DatagramSocket, but
508 // we'll assume they mean both.
509 SecurityManager sm = System.getSecurityManager();
510 if (sm != null)
511 sm.checkConnect(addr.getHostName(), getLocalPort());
512
513 return addr;
514 }
515
516 /**
517 * Returns the port number of the remote end of the socket connection. If
518 * this socket is not connected, then -1 is returned.
519 *
520 * @return The remote port this socket is connected to
521 */
522 public int getPort ()
523 {
524 if (!isConnected())
525 return 0;
526
527 try
528 {
529 if (getImpl() != null)
530 return getImpl().getPort();
531 }
532 catch (SocketException e)
533 {
534 // This cannot happen as we are connected.
535 }
536
537 return -1;
538 }
539
540 /**
541 * Returns the local port number to which this socket is bound. If this
542 * socket is not connected, then -1 is returned.
543 *
544 * @return The local port
545 */
546 public int getLocalPort ()
547 {
548 if (!isBound())
549 return -1;
550
551 try
552 {
553 if (getImpl() != null)
554 return getImpl().getLocalPort();
555 }
556 catch (SocketException e)
557 {
558 // This cannot happen as we are bound.
559 }
560
561 return -1;
562 }
563
564 /**
565 * If the socket is already bound this returns the local SocketAddress,
566 * otherwise null
567 *
568 * @since 1.4
569 */
570 public SocketAddress getLocalSocketAddress()
571 {
572 if (!isBound())
573 return null;
574
575 InetAddress addr = getLocalAddress ();
576
577 try
578 {
579 return new InetSocketAddress (addr, getImpl().getLocalPort());
580 }
581 catch (SocketException e)
582 {
583 // This cannot happen as we are bound.
584 return null;
585 }
586 }
587
588 /**
589 * If the socket is already connected this returns the remote SocketAddress,
590 * otherwise null
591 *
592 * @since 1.4
593 */
594 public SocketAddress getRemoteSocketAddress()
595 {
596 if (!isConnected ())
597 return null;
598
599 try
600 {
601 return new InetSocketAddress (getImpl().getInetAddress (), getImpl().getPort ());
602 }
603 catch (SocketException e)
604 {
605 // This cannot happen as we are connected.
606 return null;
607 }
608 }
609
610 /**
611 * Returns an InputStream for reading from this socket.
612 *
613 * @return The InputStream object
614 *
615 * @exception IOException If an error occurs or Socket is not connected
616 */
617 public InputStream getInputStream () throws IOException
618 {
619 if (isClosed())
620 throw new SocketException("socket is closed");
621
622 if (!isConnected())
623 throw new IOException("not connected");
624
625 return getImpl().getInputStream();
626 }
627
628 /**
629 * Returns an OutputStream for writing to this socket.
630 *
631 * @return The OutputStream object
632 *
633 * @exception IOException If an error occurs or Socket is not connected
634 */
635 public OutputStream getOutputStream () throws IOException
636 {
637 if (isClosed())
638 throw new SocketException("socket is closed");
639
640 if (!isConnected())
641 throw new IOException("not connected");
642
643 return getImpl().getOutputStream();
644 }
645
646 /**
647 * Sets the TCP_NODELAY option on the socket.
648 *
649 * @param on true to enable, false to disable
650 *
651 * @exception SocketException If an error occurs or Socket is not connected
652 *
653 * @since 1.1
654 */
655 public void setTcpNoDelay (boolean on) throws SocketException
656 {
657 if (isClosed())
658 throw new SocketException("socket is closed");
659
660 getImpl().setOption(SocketOptions.TCP_NODELAY, new Boolean(on));
661 }
662
663 /**
664 * Tests whether or not the TCP_NODELAY option is set on the socket.
665 * Returns true if enabled, false if disabled. When on it disables the
666 * Nagle algorithm which means that packets are always send immediatly and
667 * never merged together to reduce network trafic.
668 *
669 * @return Whether or not TCP_NODELAY is set
670 *
671 * @exception SocketException If an error occurs or Socket not connected
672 *
673 * @since 1.1
674 */
675 public boolean getTcpNoDelay() throws SocketException
676 {
677 if (isClosed())
678 throw new SocketException("socket is closed");
679
680 Object on = getImpl().getOption(SocketOptions.TCP_NODELAY);
681
682 if (on instanceof Boolean)
683 return(((Boolean)on).booleanValue());
684 else
685 throw new SocketException("Internal Error");
686 }
687
688 /**
689 * Sets the value of the SO_LINGER option on the socket. If the
690 * SO_LINGER option is set on a socket and there is still data waiting to
691 * be sent when the socket is closed, then the close operation will block
692 * until either that data is delivered or until the timeout period
693 * expires. The linger interval is specified in hundreths of a second
694 * (platform specific?)
695 *
696 * @param on true to enable SO_LINGER, false to disable
697 * @param linger The SO_LINGER timeout in hundreths of a second or -1 if
698 * SO_LINGER not set.
699 *
700 * @exception SocketException If an error occurs or Socket not connected
701 * @exception IllegalArgumentException If linger is negative
702 *
703 * @since 1.1
704 */
705 public void setSoLinger(boolean on, int linger) throws SocketException
706 {
707 if (isClosed())
708 throw new SocketException("socket is closed");
709
710 if (on == true)
711 {
712 if (linger < 0)
713 throw new IllegalArgumentException("SO_LINGER must be >= 0");
714
715 if (linger > 65535)
716 linger = 65535;
717
718 getImpl().setOption(SocketOptions.SO_LINGER, new Integer(linger));
719 }
720 else
721 {
722 getImpl().setOption(SocketOptions.SO_LINGER, new Boolean(false));
723 }
724 }
725
726 /**
727 * Returns the value of the SO_LINGER option on the socket. If the
728 * SO_LINGER option is set on a socket and there is still data waiting to
729 * be sent when the socket is closed, then the close operation will block
730 * until either that data is delivered or until the timeout period
731 * expires. This method either returns the timeouts (in hundredths of
732 * of a second (platform specific?)) if SO_LINGER is set, or -1 if
733 * SO_LINGER is not set.
734 *
735 * @return The SO_LINGER timeout in hundreths of a second or -1
736 * if SO_LINGER not set
737 *
738 * @exception SocketException If an error occurs or Socket is not connected
739 *
740 * @since 1.1
741 */
742 public int getSoLinger() throws SocketException
743 {
744 if (isClosed())
745 throw new SocketException("socket is closed");
746
747 Object linger = getImpl().getOption(SocketOptions.SO_LINGER);
748
749 if (linger instanceof Integer)
750 return(((Integer)linger).intValue());
751 else
752 return -1;
753 }
754
755 /**
756 * Sends urgent data through the socket
757 *
758 * @param data The data to send.
759 * Only the lowest eight bits of data are sent
760 *
761 * @exception IOException If an error occurs
762 *
763 * @since 1.4
764 */
765 public void sendUrgentData (int data) throws IOException
766 {
767 if (isClosed())
768 throw new SocketException("socket is closed");
769
770 getImpl().sendUrgentData (data);
771 }
772
773 /**
774 * Enables/disables the SO_OOBINLINE option
775 *
776 * @param on True if SO_OOBLINE should be enabled
777 *
778 * @exception SocketException If an error occurs
779 *
780 * @since 1.4
781 */
782 public void setOOBInline (boolean on) throws SocketException
783 {
784 if (isClosed())
785 throw new SocketException("socket is closed");
786
787 getImpl().setOption(SocketOptions.SO_OOBINLINE, new Boolean(on));
788 }
789
790 /**
791 * Returns the current setting of the SO_OOBINLINE option for this socket
792 *
793 * @return True if SO_OOBINLINE is set, false otherwise.
794 *
795 * @exception SocketException If an error occurs
796 *
797 * @since 1.4
798 */
799 public boolean getOOBInline () throws SocketException
800 {
801 if (isClosed())
802 throw new SocketException("socket is closed");
803
804 Object buf = getImpl().getOption(SocketOptions.SO_OOBINLINE);
805
806 if (buf instanceof Boolean)
807 return(((Boolean)buf).booleanValue());
808 else
809 throw new SocketException("Internal Error: Unexpected type");
810 }
811
812 /**
813 * Sets the value of the SO_TIMEOUT option on the socket. If this value
814 * is set, and an read/write is performed that does not complete within
815 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
816 * would be sent in Unix if no data had been read). A value of 0 for
817 * this option implies that there is no timeout (ie, operations will
818 * block forever). On systems that have separate read and write timeout
819 * values, this method returns the read timeout. This
820 * value is in milliseconds.
821 *
822 * @param timeout The length of the timeout in milliseconds, or
823 * 0 to indicate no timeout.
824 *
825 * @exception SocketException If an error occurs or Socket not connected
826 *
827 * @since 1.1
828 */
829 public synchronized void setSoTimeout (int timeout) throws SocketException
830 {
831 if (isClosed())
832 throw new SocketException("socket is closed");
833
834 if (timeout < 0)
835 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
836
837 getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
838 }
839
840 /**
841 * Returns the value of the SO_TIMEOUT option on the socket. If this value
842 * is set, and an read/write is performed that does not complete within
843 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
844 * would be sent in Unix if no data had been read). A value of 0 for
845 * this option implies that there is no timeout (ie, operations will
846 * block forever). On systems that have separate read and write timeout
847 * values, this method returns the read timeout. This
848 * value is in thousandths of a second (implementation specific?).
849 *
850 * @return The length of the timeout in thousandth's of a second or 0
851 * if not set
852 *
853 * @exception SocketException If an error occurs or Socket not connected
854 *
855 * @since 1.1
856 */
857 public synchronized int getSoTimeout () throws SocketException
858 {
859 if (isClosed())
860 throw new SocketException("socket is closed");
861
862 Object timeout = getImpl().getOption(SocketOptions.SO_TIMEOUT);
863 if (timeout instanceof Integer)
864 return(((Integer)timeout).intValue());
865 else
866 return 0;
867 }
868
869 /**
870 * This method sets the value for the system level socket option
871 * SO_SNDBUF to the specified value. Note that valid values for this
872 * option are specific to a given operating system.
873 *
874 * @param size The new send buffer size.
875 *
876 * @exception SocketException If an error occurs or Socket not connected
877 * @exception IllegalArgumentException If size is 0 or negative
878 *
879 * @since 1.2
880 */
881 public void setSendBufferSize (int size) throws SocketException
882 {
883 if (isClosed())
884 throw new SocketException("socket is closed");
885
886 if (size <= 0)
887 throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
888
889 getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));
890 }
891
892 /**
893 * This method returns the value of the system level socket option
894 * SO_SNDBUF, which is used by the operating system to tune buffer
895 * sizes for data transfers.
896 *
897 * @return The send buffer size.
898 *
899 * @exception SocketException If an error occurs or socket not connected
900 *
901 * @since 1.2
902 */
903 public int getSendBufferSize () throws SocketException
904 {
905 if (isClosed())
906 throw new SocketException("socket is closed");
907
908 Object buf = getImpl().getOption(SocketOptions.SO_SNDBUF);
909
910 if (buf instanceof Integer)
911 return(((Integer)buf).intValue());
912 else
913 throw new SocketException("Internal Error: Unexpected type");
914 }
915
916 /**
917 * This method sets the value for the system level socket option
918 * SO_RCVBUF to the specified value. Note that valid values for this
919 * option are specific to a given operating system.
920 *
921 * @param size The new receive buffer size.
922 *
923 * @exception SocketException If an error occurs or Socket is not connected
924 * @exception IllegalArgumentException If size is 0 or negative
925 *
926 * @since 1.2
927 */
928 public void setReceiveBufferSize (int size) throws SocketException
929 {
930 if (isClosed())
931 throw new SocketException("socket is closed");
932
933 if (size <= 0)
934 throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
935
936 getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
937 }
938
939 /**
940 * This method returns the value of the system level socket option
941 * SO_RCVBUF, which is used by the operating system to tune buffer
942 * sizes for data transfers.
943 *
944 * @return The receive buffer size.
945 *
946 * @exception SocketException If an error occurs or Socket is not connected
947 *
948 * @since 1.2
949 */
950 public int getReceiveBufferSize () throws SocketException
951 {
952 if (isClosed())
953 throw new SocketException("socket is closed");
954
955 Object buf = getImpl().getOption(SocketOptions.SO_RCVBUF);
956
957 if (buf instanceof Integer)
958 return(((Integer)buf).intValue());
959 else
960 throw new SocketException("Internal Error: Unexpected type");
961 }
962
963 /**
964 * This method sets the value for the socket level socket option
965 * SO_KEEPALIVE.
966 *
967 * @param on True if SO_KEEPALIVE should be enabled
968 *
969 * @exception SocketException If an error occurs or Socket is not connected
970 *
971 * @since 1.3
972 */
973 public void setKeepAlive (boolean on) throws SocketException
974 {
975 if (isClosed())
976 throw new SocketException("socket is closed");
977
978 getImpl().setOption(SocketOptions.SO_KEEPALIVE, new Boolean(on));
979 }
980
981 /**
982 * This method returns the value of the socket level socket option
983 * SO_KEEPALIVE.
984 *
985 * @return The setting
986 *
987 * @exception SocketException If an error occurs or Socket is not connected
988 *
989 * @since 1.3
990 */
991 public boolean getKeepAlive () throws SocketException
992 {
993 if (isClosed())
994 throw new SocketException("socket is closed");
995
996 Object buf = getImpl().getOption(SocketOptions.SO_KEEPALIVE);
997
998 if (buf instanceof Boolean)
999 return(((Boolean)buf).booleanValue());
1000 else
1001 throw new SocketException("Internal Error: Unexpected type");
1002 }
1003
1004 /**
1005 * Closes the socket.
1006 *
1007 * @exception IOException If an error occurs
1008 */
1009 public synchronized void close () throws IOException
1010 {
1011 if (isClosed())
1012 return;
1013
1014 getImpl().close();
1015 impl = null;
1016 bound = false;
1017
1018 if (getChannel() != null)
1019 getChannel().close();
1020 }
1021
1022 /**
1023 * Converts this <code>Socket</code> to a <code>String</code>.
1024 *
1025 * @return The <code>String</code> representation of this <code>Socket</code>
1026 */
1027 public String toString ()
1028 {
1029 try
1030 {
1031 if (isConnected())
1032 return ("Socket[addr=" + getImpl().getInetAddress()
1033 + ",port=" + getImpl().getPort()
1034 + ",localport=" + getImpl().getLocalPort()
1035 + "]");
1036 }
1037 catch (SocketException e)
1038 {
1039 // This cannot happen as we are connected.
1040 }
1041
1042 return "Socket[unconnected]";
1043 }
1044
1045 /**
1046 * Sets the <code>SocketImplFactory</code>. This may be done only once per
1047 * virtual machine. Subsequent attempts will generate a
1048 * <code>SocketException</code>. Note that a <code>SecurityManager</code>
1049 * check is made prior to setting the factory. If
1050 * insufficient privileges exist to set the factory, then an
1051 * <code>IOException</code> will be thrown.
1052 *
1053 * @exception SecurityException If the <code>SecurityManager</code> does
1054 * not allow this operation.
1055 * @exception SocketException If the SocketImplFactory is already defined
1056 * @exception IOException If any other error occurs
1057 */
1058 public static synchronized void setSocketImplFactory (SocketImplFactory fac)
1059 throws IOException
1060 {
1061 // See if already set
1062 if (factory != null)
1063 throw new SocketException("SocketImplFactory already defined");
1064
1065 // Check permissions
1066 SecurityManager sm = System.getSecurityManager();
1067 if (sm != null)
1068 sm.checkSetFactory();
1069
1070 if (fac == null)
1071 throw new SocketException("SocketImplFactory cannot be null");
1072
1073 factory = fac;
1074 }
1075
1076 /**
1077 * Closes the input side of the socket stream.
1078 *
1079 * @exception IOException If an error occurs.
1080 *
1081 * @since 1.3
1082 */
1083 public void shutdownInput() throws IOException
1084 {
1085 if (isClosed())
1086 throw new SocketException("socket is closed");
1087
1088 getImpl().shutdownInput();
1089 inputShutdown = true;
1090 }
1091
1092 /**
1093 * Closes the output side of the socket stream.
1094 *
1095 * @exception IOException If an error occurs.
1096 *
1097 * @since 1.3
1098 */
1099 public void shutdownOutput() throws IOException
1100 {
1101 if (isClosed())
1102 throw new SocketException("socket is closed");
1103
1104 getImpl().shutdownOutput();
1105 outputShutdown = true;
1106 }
1107
1108 /**
1109 * Returns the socket channel associated with this socket.
1110 *
1111 * It returns null if no associated socket exists.
1112 *
1113 * @since 1.4
1114 */
1115 public SocketChannel getChannel()
1116 {
1117 return null;
1118 }
1119
1120 /**
1121 * Checks if the SO_REUSEADDR option is enabled
1122 *
1123 * @return True if SO_REUSEADDR is set, false otherwise.
1124 *
1125 * @exception SocketException If an error occurs
1126 *
1127 * @since 1.4
1128 */
1129 public boolean getReuseAddress () throws SocketException
1130 {
1131 if (isClosed())
1132 throw new SocketException("socket is closed");
1133
1134 Object reuseaddr = getImpl().getOption (SocketOptions.SO_REUSEADDR);
1135
1136 if (!(reuseaddr instanceof Boolean))
1137 throw new SocketException ("Internal Error");
1138
1139 return ((Boolean) reuseaddr).booleanValue ();
1140 }
1141
1142 /**
1143 * Enables/Disables the SO_REUSEADDR option
1144 *
1145 * @param reuseAddress True if SO_REUSEADDR should be set.
1146 *
1147 * @exception SocketException If an error occurs
1148 *
1149 * @since 1.4
1150 */
1151 public void setReuseAddress (boolean on) throws SocketException
1152 {
1153 getImpl().setOption (SocketOptions.SO_REUSEADDR, new Boolean (on));
1154 }
1155
1156 /**
1157 * Returns the current traffic class
1158 *
1159 * @return The current traffic class.
1160 *
1161 * @exception SocketException If an error occurs
1162 *
1163 * @see Socket#setTrafficClass(int tc)
1164 *
1165 * @since 1.4
1166 */
1167 public int getTrafficClass () throws SocketException
1168 {
1169 if (isClosed())
1170 throw new SocketException("socket is closed");
1171
1172 Object obj = getImpl().getOption(SocketOptions.IP_TOS);
1173
1174 if (obj instanceof Integer)
1175 return ((Integer) obj).intValue ();
1176 else
1177 throw new SocketException ("Unexpected type");
1178 }
1179
1180 /**
1181 * Sets the traffic class value
1182 *
1183 * @param tc The traffic class
1184 *
1185 * @exception SocketException If an error occurs
1186 * @exception IllegalArgumentException If tc value is illegal
1187 *
1188 * @see Socket#getTrafficClass()
1189 *
1190 * @since 1.4
1191 */
1192 public void setTrafficClass (int tc) throws SocketException
1193 {
1194 if (isClosed())
1195 throw new SocketException("socket is closed");
1196
1197 if (tc < 0 || tc > 255)
1198 throw new IllegalArgumentException();
1199
1200 getImpl().setOption (SocketOptions.IP_TOS, new Integer (tc));
1201 }
1202
1203 /**
1204 * Checks if the socket is connected
1205 *
1206 * @return True if socket is connected, false otherwise.
1207 *
1208 * @since 1.4
1209 */
1210 public boolean isConnected ()
1211 {
1212 try
1213 {
1214 return getImpl().getInetAddress () != null;
1215 }
1216 catch (SocketException e)
1217 {
1218 return false;
1219 }
1220 }
1221
1222 /**
1223 * Checks if the socket is already bound.
1224 *
1225 * @return True if socket is bound, false otherwise.
1226 *
1227 * @since 1.4
1228 */
1229 public boolean isBound ()
1230 {
1231 return bound;
1232 }
1233
1234 /**
1235 * Checks if the socket is closed.
1236 *
1237 * @return True if socket is closed, false otherwise.
1238 *
1239 * @since 1.4
1240 */
1241 public boolean isClosed ()
1242 {
1243 return impl == null;
1244 }
1245
1246 /**
1247 * Checks if the socket's input stream is shutdown
1248 *
1249 * @return True if input is shut down.
1250 *
1251 * @since 1.4
1252 */
1253 public boolean isInputShutdown ()
1254 {
1255 return inputShutdown;
1256 }
1257
1258 /**
1259 * Checks if the socket's output stream is shutdown
1260 *
1261 * @return True if output is shut down.
1262 *
1263 * @since 1.4
1264 */
1265 public boolean isOutputShutdown ()
1266 {
1267 return outputShutdown;
1268 }
1269 }