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