BindException.java, [...]: add/update of some @since/@deprecated
[gcc.git] / libjava / java / net / Socket.java
1 /* Socket.java -- Client socket implementation
2 Copyright (C) 1998, 1999, 2000, 2002 Free Software Foundation, Inc.
3
4 This file is part of GNU Classpath.
5
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)
9 any later version.
10
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.
15
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
19 02111-1307 USA.
20
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
24 combination.
25
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. */
37
38 package java.net;
39
40 import java.io.*;
41
42 /* Written using on-line Java Platform 1.2 API Specification.
43 * Status: I believe all methods are implemented.
44 */
45
46 /**
47 * This class models a client site socket. A socket is a TCP/IP endpoint
48 * for network communications conceptually similar to a file handle.
49 * <p>
50 * This class does not actually do any work. Instead, it redirects all of
51 * its calls to a socket implementation object which implements the
52 * <code>SocketImpl</code> interface. The implementation class is
53 * instantiated by factory class that implements the
54 * <code>SocketImplFactory interface</code>. A default
55 * factory is provided, however the factory may be set by a call to
56 * the <code>setSocketImplFactory</code> method. Note that this may only be
57 * done once per virtual machine. If a subsequent attempt is made to set the
58 * factory, a <code>SocketException</code> will be thrown.
59 *
60 * @author Aaron M. Renn (arenn@urbanophile.com)
61 * @author Per Bothner (bothner@cygnus.com)
62 */
63 public class Socket
64 {
65
66 // Class Variables
67
68 /**
69 * This is the user SocketImplFactory for this class. If this variable is
70 * null, a default factory is used.
71 */
72 static SocketImplFactory factory;
73
74 // Instance Variables
75
76 /**
77 * The implementation object to which calls are redirected
78 */
79 SocketImpl impl;
80
81 // Constructors
82
83 /**
84 * Initializes a new instance of <code>Socket</code> object without
85 * connecting to a remote host. This useful for subclasses of socket that
86 * might want this behavior.
87 */
88 protected Socket ()
89 {
90 if (factory != null)
91 impl = factory.createSocketImpl();
92 else
93 impl = new PlainSocketImpl();
94 }
95
96 /**
97 * Initializes a new instance of <code>Socket</code> object without
98 * connecting to a remote host. This is useful for subclasses of socket
99 * that might want this behavior.
100 * <p>
101 * Additionally, this socket will be created using the supplied
102 * implementation class instead the default class or one returned by a
103 * factory. This value can be <code>null</code>, but if it is, all instance
104 * methods in <code>Socket</code> should be overridden because most of them
105 * rely on this value being populated.
106 *
107 * @param impl The <code>SocketImpl</code> to use for this
108 * <code>Socket</code>
109 *
110 * @exception SocketException If an error occurs
111 */
112 protected Socket (SocketImpl impl) throws SocketException
113 {
114 this.impl = impl;
115 }
116
117 /**
118 * Initializes a new instance of <code>Socket</code> and connects to the
119 * hostname and port specified as arguments.
120 *
121 * @param host The name of the host to connect to
122 * @param port The port number to connect to
123 *
124 * @exception UnknownHostException If the hostname cannot be resolved to a
125 * network address.
126 * @exception IOException If an error occurs
127 */
128 public Socket (String host, int port)
129 throws UnknownHostException, IOException
130 {
131 this(InetAddress.getByName(host), port, null, 0, true);
132 }
133
134 /**
135 * Initializes a new instance of <code>Socket</code> and connects to the
136 * address and port number specified as arguments.
137 *
138 * @param address The address to connect to
139 * @param port The port number to connect to
140 *
141 * @exception IOException If an error occurs
142 */
143 public Socket (InetAddress address, int port)
144 throws IOException
145 {
146 this(address, port, null, 0, true);
147 }
148
149 /**
150 * Initializes a new instance of <code>Socket</code> that connects to the
151 * named host on the specified port and binds to the specified local address
152 * and port.
153 *
154 * @param host The name of the remote host to connect to.
155 * @param port The remote port to connect to.
156 * @param loadAddr The local address to bind to.
157 * @param localPort The local port to bind to.
158 *
159 * @exception SecurityException If the <code>SecurityManager</code>
160 * exists and does not allow a connection to the specified host/port or
161 * binding to the specified local host/port.
162 * @exception IOException If a connection error occurs.
163 */
164 public Socket (String host, int port,
165 InetAddress localAddr, int localPort) throws IOException
166 {
167 this(InetAddress.getByName(host), port, localAddr, localPort, true);
168 }
169
170 /**
171 * Initializes a new instance of <code>Socket</code> and connects to the
172 * address and port number specified as arguments, plus binds to the
173 * specified local address and port.
174 *
175 * @param address The remote address to connect to
176 * @param port The remote port to connect to
177 * @param localAddr The local address to connect to
178 * @param localPort The local port to connect to
179 *
180 * @exception IOException If an error occurs
181 */
182 public Socket (InetAddress address, int port,
183 InetAddress localAddr, int localPort) throws IOException
184 {
185 this(address, port, localAddr, localPort, true);
186 }
187
188 /**
189 * Initializes a new instance of <code>Socket</code> and connects to the
190 * hostname and port specified as arguments. If the stream argument is set
191 * to <code>true</code>, then a stream socket is created. If it is
192 * <code>false</code>, a datagram socket is created.
193 *
194 * @param host The name of the host to connect to
195 * @param port The port to connect to
196 * @param stream <code>true</code> for a stream socket, <code>false</code>
197 * for a datagram socket
198 *
199 * @exception IOException If an error occurs
200 *
201 * @deprecated Use the <code>DatagramSocket</code> class to create
202 * datagram oriented sockets.
203 */
204 public Socket (String host, int port, boolean stream) throws IOException
205 {
206 this(InetAddress.getByName(host), port, null, 0, stream);
207 }
208
209 /**
210 * Initializes a new instance of <code>Socket</code> and connects to the
211 * address and port number specified as arguments. If the stream param is
212 * <code>true</code>, a stream socket will be created, otherwise a datagram
213 * socket is created.
214 *
215 * @param host The address to connect to
216 * @param port The port number to connect to
217 * @param stream <code>true</code> to create a stream socket,
218 * <code>false</code> to create a datagram socket.
219 *
220 * @exception IOException If an error occurs
221 *
222 * @deprecated Use the <code>DatagramSocket</code> class to create
223 * datagram oriented sockets.
224 */
225 public Socket (InetAddress host, int port, boolean stream) throws IOException
226 {
227 this(host, port, null, 0, stream);
228 }
229
230 /**
231 * This constructor is where the real work takes place. Connect to the
232 * specified address and port. Use default local values if not specified,
233 * otherwise use the local host and port passed in. Create as stream or
234 * datagram based on "stream" argument.
235 * <p>
236 *
237 * @param raddr The remote address to connect to
238 * @param rport The remote port to connect to
239 * @param laddr The local address to connect to
240 * @param lport The local port to connect to
241 * @param stream true for a stream socket, false for a datagram socket
242 *
243 * @exception IOException If an error occurs
244 */
245 private Socket(InetAddress raddr, int rport, InetAddress laddr, int lport,
246 boolean stream) throws IOException
247 {
248 this();
249 if (impl == null)
250 throw new IOException("Cannot initialize Socket implementation");
251
252 SecurityManager sm = System.getSecurityManager();
253 if (sm != null)
254 sm.checkConnect(raddr.getHostName(), rport);
255
256 impl.create(stream);
257
258 // FIXME: JCL p. 1586 says if localPort is unspecified, bind to any port,
259 // i.e. '0' and if localAddr is unspecified, use getLocalAddress() as
260 // that default. JDK 1.2 doc infers not to do a bind.
261 if (laddr != null)
262 impl.bind(laddr, lport);
263
264 if (raddr != null)
265 impl.connect(raddr, rport);
266 }
267
268 /**
269 * Returns the address of the remote end of the socket. If this socket
270 * is not connected, then <code>null</code> is returned.
271 *
272 * @return The remote address this socket is connected to
273 */
274 public InetAddress getInetAddress ()
275 {
276 if (impl != null)
277 return impl.getInetAddress();
278
279 return null;
280 }
281
282 /**
283 * Returns the local address to which this socket is bound. If this socket
284 * is not connected, then <code>null</code> is returned.
285 *
286 * @return The local address
287 */
288 public InetAddress getLocalAddress ()
289 {
290 if (impl == null)
291 return null;
292
293 InetAddress addr = null;
294 try
295 {
296 addr = (InetAddress)impl.getOption(SocketOptions.SO_BINDADDR);
297 }
298 catch(SocketException e)
299 {
300 // (hopefully) shouldn't happen
301 // throw new java.lang.InternalError
302 // ("Error in PlainSocketImpl.getOption");
303 return null;
304 }
305
306 // FIXME: According to libgcj, checkConnect() is supposed to be called
307 // before performing this operation. Problems: 1) We don't have the
308 // addr until after we do it, so we do a post check. 2). The docs I
309 // see don't require this in the Socket case, only DatagramSocket, but
310 // we'll assume they mean both.
311 SecurityManager sm = System.getSecurityManager();
312 if (sm != null)
313 sm.checkConnect(addr.getHostName(), getLocalPort());
314
315 return addr;
316 }
317
318 /**
319 * Returns the port number of the remote end of the socket connection. If
320 * this socket is not connected, then -1 is returned.
321 *
322 * @return The remote port this socket is connected to
323 */
324 public int getPort ()
325 {
326 if (impl != null)
327 return impl.getPort();
328
329 return -1;
330 }
331
332 /**
333 * Returns the local port number to which this socket is bound. If this
334 * socket is not connected, then -1 is returned.
335 *
336 * @return The local port
337 */
338 public int getLocalPort ()
339 {
340 if (impl != null)
341 return impl.getLocalPort();
342
343 return -1;
344 }
345
346 /**
347 * Returns an InputStream for reading from this socket.
348 *
349 * @return The InputStream object
350 *
351 * @exception IOException If an error occurs or Socket is not connected
352 */
353 public InputStream getInputStream () throws IOException
354 {
355 if (impl != null)
356 return(impl.getInputStream());
357
358 throw new IOException("Not connected");
359 }
360
361 /**
362 * Returns an OutputStream for writing to this socket.
363 *
364 * @return The OutputStream object
365 *
366 * @exception IOException If an error occurs or Socket is not connected
367 */
368 public OutputStream getOutputStream () throws IOException
369 {
370 if (impl != null)
371 return impl.getOutputStream();
372
373 throw new IOException("Not connected");
374 }
375
376 /**
377 * Sets the TCP_NODELAY option on the socket.
378 *
379 * @param on true to enable, false to disable
380 *
381 * @exception SocketException If an error occurs or Socket is not connected
382 */
383 public void setTcpNoDelay (boolean on) throws SocketException
384 {
385 if (impl == null)
386 throw new SocketException("Not connected");
387
388 impl.setOption(SocketOptions.TCP_NODELAY, new Boolean(on));
389 }
390
391 /**
392 * Tests whether or not the TCP_NODELAY option is set on the socket.
393 * Returns true if enabled, false if disabled. When on it disables the
394 * Nagle algorithm which means that packets are always send immediatly and
395 * never merged together to reduce network trafic.
396 *
397 * @return Whether or not TCP_NODELAY is set
398 *
399 * @exception SocketException If an error occurs or Socket not connected
400 */
401 public boolean getTcpNoDelay() throws SocketException
402 {
403 if (impl == null)
404 throw new SocketException("Not connected");
405
406 Object on = impl.getOption(SocketOptions.TCP_NODELAY);
407
408 if (on instanceof Boolean)
409 return(((Boolean)on).booleanValue());
410 else
411 throw new SocketException("Internal Error");
412 }
413
414 /**
415 * Sets the value of the SO_LINGER option on the socket. If the
416 * SO_LINGER option is set on a socket and there is still data waiting to
417 * be sent when the socket is closed, then the close operation will block
418 * until either that data is delivered or until the timeout period
419 * expires. The linger interval is specified in hundreths of a second
420 * (platform specific?)
421 *
422 * @param on true to enable SO_LINGER, false to disable
423 * @param linger The SO_LINGER timeout in hundreths of a second or -1 if
424 * SO_LINGER not set.
425 *
426 * @exception SocketException If an error occurs or Socket not connected
427 */
428 public void setSoLinger(boolean on, int linger) throws SocketException
429 {
430 if (impl == null)
431 throw new SocketException("No socket created");
432
433 if (on == true)
434 {
435 if (linger < 0)
436 throw new IllegalArgumentException("SO_LINGER must be >= 0");
437
438 if (linger > 65535)
439 linger = 65535;
440
441 impl.setOption(SocketOptions.SO_LINGER, new Integer(linger));
442 }
443 else
444 {
445 impl.setOption(SocketOptions.SO_LINGER, new Boolean(false));
446 }
447 }
448
449 /**
450 * Returns the value of the SO_LINGER option on the socket. If the
451 * SO_LINGER option is set on a socket and there is still data waiting to
452 * be sent when the socket is closed, then the close operation will block
453 * until either that data is delivered or until the timeout period
454 * expires. This method either returns the timeouts (in hundredths of
455 * of a second (platform specific?)) if SO_LINGER is set, or -1 if
456 * SO_LINGER is not set.
457 *
458 * @return The SO_LINGER timeout in hundreths of a second or -1
459 * if SO_LINGER not set
460 *
461 * @exception SocketException If an error occurs or Socket is not connected
462 */
463 public int getSoLinger() throws SocketException
464 {
465 if (impl == null)
466 throw new SocketException("Not connected");
467
468 Object linger = impl.getOption(SocketOptions.SO_LINGER);
469 if (linger instanceof Integer)
470 return(((Integer)linger).intValue());
471 else
472 return -1;
473 }
474
475 /**
476 * Sets the value of the SO_TIMEOUT option on the socket. If this value
477 * is set, and an read/write is performed that does not complete within
478 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
479 * would be sent in Unix if no data had been read). A value of 0 for
480 * this option implies that there is no timeout (ie, operations will
481 * block forever). On systems that have separate read and write timeout
482 * values, this method returns the read timeout. This
483 * value is in thousandths of a second (****????*****)
484 *
485 * @param timeout The length of the timeout in thousandth's of a second or
486 * 0 if not set
487 *
488 * @exception SocketException If an error occurs or Socket not connected
489 */
490 public synchronized void setSoTimeout (int timeout) throws SocketException
491 {
492 if (impl == null)
493 throw new SocketException("Not connected");
494
495 if (timeout < 0)
496 throw new IllegalArgumentException("SO_TIMEOUT value must be >= 0");
497
498 impl.setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
499 }
500
501 /**
502 * Returns the value of the SO_TIMEOUT option on the socket. If this value
503 * is set, and an read/write is performed that does not complete within
504 * the timeout period, a short count is returned (or an EWOULDBLOCK signal
505 * would be sent in Unix if no data had been read). A value of 0 for
506 * this option implies that there is no timeout (ie, operations will
507 * block forever). On systems that have separate read and write timeout
508 * values, this method returns the read timeout. This
509 * value is in thousandths of a second (implementation specific?).
510 *
511 * @return The length of the timeout in thousandth's of a second or 0
512 * if not set
513 *
514 * @exception SocketException If an error occurs or Socket not connected
515 */
516 public synchronized int getSoTimeout () throws SocketException
517 {
518 if (impl == null)
519 throw new SocketException("Not connected");
520
521 Object timeout = impl.getOption(SocketOptions.SO_TIMEOUT);
522 if (timeout instanceof Integer)
523 return(((Integer)timeout).intValue());
524 else
525 return 0;
526 }
527
528 /**
529 * This method sets the value for the system level socket option
530 * SO_SNDBUF to the specified value. Note that valid values for this
531 * option are specific to a given operating system.
532 *
533 * @param size The new send buffer size.
534 *
535 * @exception SocketException If an error occurs or Socket not connected
536 *
537 * @since 1.2
538 */
539 public void setSendBufferSize (int size) throws SocketException
540 {
541 if (impl == null)
542 throw new SocketException("Not connected");
543
544 if (size <= 0)
545 throw new IllegalArgumentException("SO_SNDBUF value must be > 0");
546
547 impl.setOption(SocketOptions.SO_SNDBUF, new Integer(size));
548 }
549
550 /**
551 * This method returns the value of the system level socket option
552 * SO_SNDBUF, which is used by the operating system to tune buffer
553 * sizes for data transfers.
554 *
555 * @return The send buffer size.
556 *
557 * @exception SocketException If an error occurs or socket not connected
558 *
559 * @since 1.2
560 */
561 public int getSendBufferSize () throws SocketException
562 {
563 if (impl == null)
564 throw new SocketException("Not connected");
565
566 Object buf = impl.getOption(SocketOptions.SO_SNDBUF);
567
568 if (buf instanceof Integer)
569 return(((Integer)buf).intValue());
570 else
571 throw new SocketException("Internal Error: Unexpected type");
572 }
573
574 /**
575 * This method sets the value for the system level socket option
576 * SO_RCVBUF to the specified value. Note that valid values for this
577 * option are specific to a given operating system.
578 *
579 * @param size The new receive buffer size.
580 *
581 * @exception SocketException If an error occurs or Socket is not connected
582 *
583 * @since 1.2
584 */
585 public void setReceiveBufferSize (int size) throws SocketException
586 {
587 if (impl == null)
588 throw new SocketException("Not connected");
589
590 if (size <= 0)
591 throw new IllegalArgumentException("SO_RCVBUF value must be > 0");
592
593 impl.setOption(SocketOptions.SO_RCVBUF, new Integer(size));
594 }
595
596 /**
597 * This method returns the value of the system level socket option
598 * SO_RCVBUF, which is used by the operating system to tune buffer
599 * sizes for data transfers.
600 *
601 * @return The receive buffer size.
602 *
603 * @exception SocketException If an error occurs or Socket is not connected
604 *
605 * @since 1.2
606 */
607 public int getReceiveBufferSize () throws SocketException
608 {
609 if (impl == null)
610 throw new SocketException("Not connected");
611
612 Object buf = impl.getOption(SocketOptions.SO_RCVBUF);
613
614 if (buf instanceof Integer)
615 return(((Integer)buf).intValue());
616 else
617 throw new SocketException("Internal Error: Unexpected type");
618 }
619
620 /**
621 * Closes the socket.
622 *
623 * @exception IOException If an error occurs
624 */
625 public synchronized void close () throws IOException
626 {
627 if (impl != null)
628 impl.close();
629 }
630
631 /**
632 * Converts this <code>Socket</code> to a <code>String</code>.
633 *
634 * @return The <code>String</code> representation of this <code>Socket</code>
635 */
636 public String toString ()
637 {
638 return("Socket " + impl);
639 }
640
641 // Class Methods
642
643 /**
644 * Sets the <code>SocketImplFactory</code>. This may be done only once per
645 * virtual machine. Subsequent attempts will generate a
646 * <code>SocketException</code>. Note that a <code>SecurityManager</code>
647 * check is made prior to setting the factory. If
648 * insufficient privileges exist to set the factory, then an
649 * <code>IOException</code> will be thrown.
650 *
651 * @exception SecurityException If the <code>SecurityManager</code> does
652 * not allow this operation.
653 * @exception SocketException If the SocketImplFactory is already defined
654 * @exception IOException If any other error occurs
655 */
656 public static synchronized void setSocketImplFactory (SocketImplFactory fac)
657 throws IOException
658 {
659 // See if already set
660 if (factory != null)
661 throw new SocketException("SocketImplFactory already defined");
662
663 // Check permissions
664 SecurityManager sm = System.getSecurityManager();
665 if (sm != null)
666 sm.checkSetFactory();
667
668 factory = fac;
669 }
670 }