]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/tcp.rs
change the format of the linked issue number
[rust.git] / src / libstd / net / tcp.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use io::prelude::*;
12
13 use fmt;
14 use io;
15 use net::{ToSocketAddrs, SocketAddr, Shutdown};
16 use sys_common::net as net_imp;
17 use sys_common::{AsInner, FromInner, IntoInner};
18 use time::Duration;
19
20 /// A TCP stream between a local and a remote socket.
21 ///
22 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
23 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
24 /// by [reading] and [writing] to it.
25 ///
26 /// The connection will be closed when the value is dropped. The reading and writing
27 /// portions of the connection can also be shut down individually with the [`shutdown`]
28 /// method.
29 ///
30 /// The Transmission Control Protocol is specified in [IETF RFC 793].
31 ///
32 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
33 /// [`connect`]: #method.connect
34 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
35 /// [reading]: ../../std/io/trait.Read.html
36 /// [`shutdown`]: #method.shutdown
37 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
38 /// [writing]: ../../std/io/trait.Write.html
39 ///
40 /// # Examples
41 ///
42 /// ```no_run
43 /// use std::io::prelude::*;
44 /// use std::net::TcpStream;
45 ///
46 /// {
47 ///     let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
48 ///
49 ///     // ignore the Result
50 ///     let _ = stream.write(&[1]);
51 ///     let _ = stream.read(&mut [0; 128]); // ignore here too
52 /// } // the stream is closed here
53 /// ```
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct TcpStream(net_imp::TcpStream);
56
57 /// A TCP socket server, listening for connections.
58 ///
59 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
60 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
61 /// iterating over the [`Incoming`] iterator returned by [`incoming`].
62 ///
63 /// The socket will be closed when the value is dropped.
64 ///
65 /// The Transmission Control Protocol is specified in [IETF RFC 793].
66 ///
67 /// [`accept`]: #method.accept
68 /// [`bind`]: #method.bind
69 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
70 /// [`Incoming`]: ../../std/net/struct.Incoming.html
71 /// [`incoming`]: #method.incoming
72 ///
73 /// # Examples
74 ///
75 /// ```no_run
76 /// use std::net::{TcpListener, TcpStream};
77 ///
78 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
79 ///
80 /// fn handle_client(stream: TcpStream) {
81 ///     // ...
82 /// }
83 ///
84 /// // accept connections and process them serially
85 /// for stream in listener.incoming() {
86 ///     match stream {
87 ///         Ok(stream) => {
88 ///             handle_client(stream);
89 ///         }
90 ///         Err(e) => { /* connection failed */ }
91 ///     }
92 /// }
93 /// ```
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct TcpListener(net_imp::TcpListener);
96
97 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
98 ///
99 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
100 /// See its documentation for more.
101 ///
102 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
103 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
104 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
105 #[stable(feature = "rust1", since = "1.0.0")]
106 #[derive(Debug)]
107 pub struct Incoming<'a> { listener: &'a TcpListener }
108
109 impl TcpStream {
110     /// Opens a TCP connection to a remote host.
111     ///
112     /// `addr` is an address of the remote host. Anything which implements
113     /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
114     /// documentation for concrete examples.
115     /// In case [`ToSocketAddrs::to_socket_addrs()`] returns more than one entry,
116     /// then the first valid and reachable address is used.
117     ///
118     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
119     /// [`ToSocketAddrs::to_socket_addrs()`]:
120     /// ../../std/net/trait.ToSocketAddrs.html#tymethod.to_socket_addrs
121     ///
122     /// # Examples
123     ///
124     /// ```no_run
125     /// use std::net::TcpStream;
126     ///
127     /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
128     ///     println!("Connected to the server!");
129     /// } else {
130     ///     println!("Couldn't connect to server...");
131     /// }
132     /// ```
133     #[stable(feature = "rust1", since = "1.0.0")]
134     pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
135         super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
136     }
137
138     /// Returns the socket address of the remote peer of this TCP connection.
139     ///
140     /// # Examples
141     ///
142     /// ```no_run
143     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
144     ///
145     /// let stream = TcpStream::connect("127.0.0.1:8080")
146     ///                        .expect("Couldn't connect to the server...");
147     /// assert_eq!(stream.peer_addr().unwrap(),
148     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
149     /// ```
150     #[stable(feature = "rust1", since = "1.0.0")]
151     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
152         self.0.peer_addr()
153     }
154
155     /// Returns the socket address of the local half of this TCP connection.
156     ///
157     /// # Examples
158     ///
159     /// ```no_run
160     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
161     ///
162     /// let stream = TcpStream::connect("127.0.0.1:8080")
163     ///                        .expect("Couldn't connect to the server...");
164     /// assert_eq!(stream.local_addr().unwrap(),
165     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
166     /// ```
167     #[stable(feature = "rust1", since = "1.0.0")]
168     pub fn local_addr(&self) -> io::Result<SocketAddr> {
169         self.0.socket_addr()
170     }
171
172     /// Shuts down the read, write, or both halves of this connection.
173     ///
174     /// This function will cause all pending and future I/O on the specified
175     /// portions to return immediately with an appropriate value (see the
176     /// documentation of [`Shutdown`]).
177     ///
178     /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
179     ///
180     /// # Examples
181     ///
182     /// ```no_run
183     /// use std::net::{Shutdown, TcpStream};
184     ///
185     /// let stream = TcpStream::connect("127.0.0.1:8080")
186     ///                        .expect("Couldn't connect to the server...");
187     /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
188     /// ```
189     #[stable(feature = "rust1", since = "1.0.0")]
190     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
191         self.0.shutdown(how)
192     }
193
194     /// Creates a new independently owned handle to the underlying socket.
195     ///
196     /// The returned `TcpStream` is a reference to the same stream that this
197     /// object references. Both handles will read and write the same stream of
198     /// data, and options set on one stream will be propagated to the other
199     /// stream.
200     ///
201     /// # Examples
202     ///
203     /// ```no_run
204     /// use std::net::TcpStream;
205     ///
206     /// let stream = TcpStream::connect("127.0.0.1:8080")
207     ///                        .expect("Couldn't connect to the server...");
208     /// let stream_clone = stream.try_clone().expect("clone failed...");
209     /// ```
210     #[stable(feature = "rust1", since = "1.0.0")]
211     pub fn try_clone(&self) -> io::Result<TcpStream> {
212         self.0.duplicate().map(TcpStream)
213     }
214
215     /// Sets the read timeout to the timeout specified.
216     ///
217     /// If the value specified is [`None`], then [`read`] calls will block
218     /// indefinitely. It is an error to pass the zero `Duration` to this
219     /// method.
220     ///
221     /// # Note
222     ///
223     /// Platforms may return a different error code whenever a read times out as
224     /// a result of setting this option. For example Unix typically returns an
225     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
226     ///
227     /// [`None`]: ../../std/option/enum.Option.html#variant.None
228     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
229     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
230     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
231     ///
232     /// # Examples
233     ///
234     /// ```no_run
235     /// use std::net::TcpStream;
236     ///
237     /// let stream = TcpStream::connect("127.0.0.1:8080")
238     ///                        .expect("Couldn't connect to the server...");
239     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
240     /// ```
241     #[stable(feature = "socket_timeout", since = "1.4.0")]
242     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
243         self.0.set_read_timeout(dur)
244     }
245
246     /// Sets the write timeout to the timeout specified.
247     ///
248     /// If the value specified is [`None`], then [`write`] calls will block
249     /// indefinitely. It is an error to pass the zero [`Duration`] to this
250     /// method.
251     ///
252     /// # Note
253     ///
254     /// Platforms may return a different error code whenever a write times out
255     /// as a result of setting this option. For example Unix typically returns
256     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
257     ///
258     /// [`None`]: ../../std/option/enum.Option.html#variant.None
259     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
260     /// [`Duration`]: ../../std/time/struct.Duration.html
261     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
262     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
263     ///
264     /// # Examples
265     ///
266     /// ```no_run
267     /// use std::net::TcpStream;
268     ///
269     /// let stream = TcpStream::connect("127.0.0.1:8080")
270     ///                        .expect("Couldn't connect to the server...");
271     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
272     /// ```
273     #[stable(feature = "socket_timeout", since = "1.4.0")]
274     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
275         self.0.set_write_timeout(dur)
276     }
277
278     /// Returns the read timeout of this socket.
279     ///
280     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
281     ///
282     /// # Note
283     ///
284     /// Some platforms do not provide access to the current timeout.
285     ///
286     /// [`None`]: ../../std/option/enum.Option.html#variant.None
287     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
288     ///
289     /// # Examples
290     ///
291     /// ```no_run
292     /// use std::net::TcpStream;
293     ///
294     /// let stream = TcpStream::connect("127.0.0.1:8080")
295     ///                        .expect("Couldn't connect to the server...");
296     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
297     /// assert_eq!(stream.read_timeout().unwrap(), None);
298     /// ```
299     #[stable(feature = "socket_timeout", since = "1.4.0")]
300     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
301         self.0.read_timeout()
302     }
303
304     /// Returns the write timeout of this socket.
305     ///
306     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
307     ///
308     /// # Note
309     ///
310     /// Some platforms do not provide access to the current timeout.
311     ///
312     /// [`None`]: ../../std/option/enum.Option.html#variant.None
313     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
314     ///
315     /// # Examples
316     ///
317     /// ```no_run
318     /// use std::net::TcpStream;
319     ///
320     /// let stream = TcpStream::connect("127.0.0.1:8080")
321     ///                        .expect("Couldn't connect to the server...");
322     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
323     /// assert_eq!(stream.write_timeout().unwrap(), None);
324     /// ```
325     #[stable(feature = "socket_timeout", since = "1.4.0")]
326     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
327         self.0.write_timeout()
328     }
329
330     /// Receives data on the socket from the remote adress to which it is
331     /// connected, without removing that data from the queue. On success,
332     /// returns the number of bytes peeked.
333     ///
334     /// Successive calls return the same data. This is accomplished by passing
335     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
336     ///
337     /// # Examples
338     ///
339     /// ```no_run
340     /// #![feature(peek)]
341     /// use std::net::TcpStream;
342     ///
343     /// let stream = TcpStream::connect("127.0.0.1:8000")
344     ///                        .expect("couldn't bind to address");
345     /// let mut buf = [0; 10];
346     /// let len = stream.peek(&mut buf).expect("peek failed");
347     /// ```
348     #[unstable(feature = "peek", issue = "38980")]
349     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
350         self.0.peek(buf)
351     }
352
353     /// Sets the value of the `TCP_NODELAY` option on this socket.
354     ///
355     /// If set, this option disables the Nagle algorithm. This means that
356     /// segments are always sent as soon as possible, even if there is only a
357     /// small amount of data. When not set, data is buffered until there is a
358     /// sufficient amount to send out, thereby avoiding the frequent sending of
359     /// small packets.
360     ///
361     /// # Examples
362     ///
363     /// ```no_run
364     /// use std::net::TcpStream;
365     ///
366     /// let stream = TcpStream::connect("127.0.0.1:8080")
367     ///                        .expect("Couldn't connect to the server...");
368     /// stream.set_nodelay(true).expect("set_nodelay call failed");
369     /// ```
370     #[stable(feature = "net2_mutators", since = "1.9.0")]
371     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
372         self.0.set_nodelay(nodelay)
373     }
374
375     /// Gets the value of the `TCP_NODELAY` option on this socket.
376     ///
377     /// For more information about this option, see [`set_nodelay`][link].
378     ///
379     /// [link]: #method.set_nodelay
380     ///
381     /// # Examples
382     ///
383     /// ```no_run
384     /// use std::net::TcpStream;
385     ///
386     /// let stream = TcpStream::connect("127.0.0.1:8080")
387     ///                        .expect("Couldn't connect to the server...");
388     /// stream.set_nodelay(true).expect("set_nodelay call failed");
389     /// assert_eq!(stream.nodelay().unwrap_or(false), true);
390     /// ```
391     #[stable(feature = "net2_mutators", since = "1.9.0")]
392     pub fn nodelay(&self) -> io::Result<bool> {
393         self.0.nodelay()
394     }
395
396     /// Sets the value for the `IP_TTL` option on this socket.
397     ///
398     /// This value sets the time-to-live field that is used in every packet sent
399     /// from this socket.
400     ///
401     /// # Examples
402     ///
403     /// ```no_run
404     /// use std::net::TcpStream;
405     ///
406     /// let stream = TcpStream::connect("127.0.0.1:8080")
407     ///                        .expect("Couldn't connect to the server...");
408     /// stream.set_ttl(100).expect("set_ttl call failed");
409     /// ```
410     #[stable(feature = "net2_mutators", since = "1.9.0")]
411     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
412         self.0.set_ttl(ttl)
413     }
414
415     /// Gets the value of the `IP_TTL` option for this socket.
416     ///
417     /// For more information about this option, see [`set_ttl`][link].
418     ///
419     /// [link]: #method.set_ttl
420     ///
421     /// # Examples
422     ///
423     /// ```no_run
424     /// use std::net::TcpStream;
425     ///
426     /// let stream = TcpStream::connect("127.0.0.1:8080")
427     ///                        .expect("Couldn't connect to the server...");
428     /// stream.set_ttl(100).expect("set_ttl call failed");
429     /// assert_eq!(stream.ttl().unwrap_or(0), 100);
430     /// ```
431     #[stable(feature = "net2_mutators", since = "1.9.0")]
432     pub fn ttl(&self) -> io::Result<u32> {
433         self.0.ttl()
434     }
435
436     /// Get the value of the `SO_ERROR` option on this socket.
437     ///
438     /// This will retrieve the stored error in the underlying socket, clearing
439     /// the field in the process. This can be useful for checking errors between
440     /// calls.
441     ///
442     /// # Examples
443     ///
444     /// ```no_run
445     /// use std::net::TcpStream;
446     ///
447     /// let stream = TcpStream::connect("127.0.0.1:8080")
448     ///                        .expect("Couldn't connect to the server...");
449     /// stream.take_error().expect("No error was expected...");
450     /// ```
451     #[stable(feature = "net2_mutators", since = "1.9.0")]
452     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
453         self.0.take_error()
454     }
455
456     /// Moves this TCP stream into or out of nonblocking mode.
457     ///
458     /// On Unix this corresponds to calling fcntl, and on Windows this
459     /// corresponds to calling ioctlsocket.
460     ///
461     /// # Examples
462     ///
463     /// ```no_run
464     /// use std::net::TcpStream;
465     ///
466     /// let stream = TcpStream::connect("127.0.0.1:8080")
467     ///                        .expect("Couldn't connect to the server...");
468     /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
469     /// ```
470     #[stable(feature = "net2_mutators", since = "1.9.0")]
471     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
472         self.0.set_nonblocking(nonblocking)
473     }
474 }
475
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl Read for TcpStream {
478     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
479     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
480         self.0.read_to_end(buf)
481     }
482 }
483 #[stable(feature = "rust1", since = "1.0.0")]
484 impl Write for TcpStream {
485     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
486     fn flush(&mut self) -> io::Result<()> { Ok(()) }
487 }
488 #[stable(feature = "rust1", since = "1.0.0")]
489 impl<'a> Read for &'a TcpStream {
490     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
491     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
492         self.0.read_to_end(buf)
493     }
494 }
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl<'a> Write for &'a TcpStream {
497     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
498     fn flush(&mut self) -> io::Result<()> { Ok(()) }
499 }
500
501 impl AsInner<net_imp::TcpStream> for TcpStream {
502     fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
503 }
504
505 impl FromInner<net_imp::TcpStream> for TcpStream {
506     fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
507 }
508
509 impl IntoInner<net_imp::TcpStream> for TcpStream {
510     fn into_inner(self) -> net_imp::TcpStream { self.0 }
511 }
512
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl fmt::Debug for TcpStream {
515     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516         self.0.fmt(f)
517     }
518 }
519
520 impl TcpListener {
521     /// Creates a new `TcpListener` which will be bound to the specified
522     /// address.
523     ///
524     /// The returned listener is ready for accepting connections.
525     ///
526     /// Binding with a port number of 0 will request that the OS assigns a port
527     /// to this listener. The port allocated can be queried via the
528     /// [`local_addr`] method.
529     ///
530     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
531     /// its documentation for concrete examples.
532     ///
533     /// [`local_addr`]: #method.local_addr
534     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
535     ///
536     /// # Examples
537     ///
538     /// ```no_run
539     /// use std::net::TcpListener;
540     ///
541     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
542     /// ```
543     #[stable(feature = "rust1", since = "1.0.0")]
544     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
545         super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
546     }
547
548     /// Returns the local socket address of this listener.
549     ///
550     /// # Examples
551     ///
552     /// ```no_run
553     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
554     ///
555     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
556     /// assert_eq!(listener.local_addr().unwrap(),
557     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
558     /// ```
559     #[stable(feature = "rust1", since = "1.0.0")]
560     pub fn local_addr(&self) -> io::Result<SocketAddr> {
561         self.0.socket_addr()
562     }
563
564     /// Creates a new independently owned handle to the underlying socket.
565     ///
566     /// The returned [`TcpListener`] is a reference to the same socket that this
567     /// object references. Both handles can be used to accept incoming
568     /// connections and options set on one listener will affect the other.
569     ///
570     /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
571     ///
572     /// # Examples
573     ///
574     /// ```no_run
575     /// use std::net::TcpListener;
576     ///
577     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
578     /// let listener_clone = listener.try_clone().unwrap();
579     /// ```
580     #[stable(feature = "rust1", since = "1.0.0")]
581     pub fn try_clone(&self) -> io::Result<TcpListener> {
582         self.0.duplicate().map(TcpListener)
583     }
584
585     /// Accept a new incoming connection from this listener.
586     ///
587     /// This function will block the calling thread until a new TCP connection
588     /// is established. When established, the corresponding [`TcpStream`] and the
589     /// remote peer's address will be returned.
590     ///
591     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
592     ///
593     /// # Examples
594     ///
595     /// ```no_run
596     /// use std::net::TcpListener;
597     ///
598     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
599     /// match listener.accept() {
600     ///     Ok((_socket, addr)) => println!("new client: {:?}", addr),
601     ///     Err(e) => println!("couldn't get client: {:?}", e),
602     /// }
603     /// ```
604     #[stable(feature = "rust1", since = "1.0.0")]
605     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
606         self.0.accept().map(|(a, b)| (TcpStream(a), b))
607     }
608
609     /// Returns an iterator over the connections being received on this
610     /// listener.
611     ///
612     /// The returned iterator will never return [`None`] and will also not yield
613     /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
614     /// calling [`accept`] in a loop.
615     ///
616     /// [`None`]: ../../std/option/enum.Option.html#variant.None
617     /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
618     /// [`accept`]: #method.accept
619     ///
620     /// # Examples
621     ///
622     /// ```no_run
623     /// use std::net::TcpListener;
624     ///
625     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
626     ///
627     /// for stream in listener.incoming() {
628     ///     match stream {
629     ///         Ok(stream) => {
630     ///             println!("new client!");
631     ///         }
632     ///         Err(e) => { /* connection failed */ }
633     ///     }
634     /// }
635     /// ```
636     #[stable(feature = "rust1", since = "1.0.0")]
637     pub fn incoming(&self) -> Incoming {
638         Incoming { listener: self }
639     }
640
641     /// Sets the value for the `IP_TTL` option on this socket.
642     ///
643     /// This value sets the time-to-live field that is used in every packet sent
644     /// from this socket.
645     ///
646     /// # Examples
647     ///
648     /// ```no_run
649     /// use std::net::TcpListener;
650     ///
651     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
652     /// listener.set_ttl(100).expect("could not set TTL");
653     /// ```
654     #[stable(feature = "net2_mutators", since = "1.9.0")]
655     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
656         self.0.set_ttl(ttl)
657     }
658
659     /// Gets the value of the `IP_TTL` option for this socket.
660     ///
661     /// For more information about this option, see [`set_ttl`][link].
662     ///
663     /// [link]: #method.set_ttl
664     ///
665     /// # Examples
666     ///
667     /// ```no_run
668     /// use std::net::TcpListener;
669     ///
670     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
671     /// listener.set_ttl(100).expect("could not set TTL");
672     /// assert_eq!(listener.ttl().unwrap_or(0), 100);
673     /// ```
674     #[stable(feature = "net2_mutators", since = "1.9.0")]
675     pub fn ttl(&self) -> io::Result<u32> {
676         self.0.ttl()
677     }
678
679     #[stable(feature = "net2_mutators", since = "1.9.0")]
680     #[rustc_deprecated(since = "1.16.0",
681                        reason = "this option can only be set before the socket is bound")]
682     #[allow(missing_docs)]
683     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
684         self.0.set_only_v6(only_v6)
685     }
686
687     #[stable(feature = "net2_mutators", since = "1.9.0")]
688     #[rustc_deprecated(since = "1.16.0",
689                        reason = "this option can only be set before the socket is bound")]
690     #[allow(missing_docs)]
691     pub fn only_v6(&self) -> io::Result<bool> {
692         self.0.only_v6()
693     }
694
695     /// Get the value of the `SO_ERROR` option on this socket.
696     ///
697     /// This will retrieve the stored error in the underlying socket, clearing
698     /// the field in the process. This can be useful for checking errors between
699     /// calls.
700     ///
701     /// # Examples
702     ///
703     /// ```no_run
704     /// use std::net::TcpListener;
705     ///
706     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
707     /// listener.take_error().expect("No error was expected");
708     /// ```
709     #[stable(feature = "net2_mutators", since = "1.9.0")]
710     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
711         self.0.take_error()
712     }
713
714     /// Moves this TCP stream into or out of nonblocking mode.
715     ///
716     /// On Unix this corresponds to calling fcntl, and on Windows this
717     /// corresponds to calling ioctlsocket.
718     ///
719     /// # Examples
720     ///
721     /// ```no_run
722     /// use std::net::TcpListener;
723     ///
724     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
725     /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
726     /// ```
727     #[stable(feature = "net2_mutators", since = "1.9.0")]
728     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
729         self.0.set_nonblocking(nonblocking)
730     }
731 }
732
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<'a> Iterator for Incoming<'a> {
735     type Item = io::Result<TcpStream>;
736     fn next(&mut self) -> Option<io::Result<TcpStream>> {
737         Some(self.listener.accept().map(|p| p.0))
738     }
739 }
740
741 impl AsInner<net_imp::TcpListener> for TcpListener {
742     fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
743 }
744
745 impl FromInner<net_imp::TcpListener> for TcpListener {
746     fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
747         TcpListener(inner)
748     }
749 }
750
751 impl IntoInner<net_imp::TcpListener> for TcpListener {
752     fn into_inner(self) -> net_imp::TcpListener { self.0 }
753 }
754
755 #[stable(feature = "rust1", since = "1.0.0")]
756 impl fmt::Debug for TcpListener {
757     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
758         self.0.fmt(f)
759     }
760 }
761
762 #[cfg(all(test, not(target_os = "emscripten")))]
763 mod tests {
764     use io::ErrorKind;
765     use io::prelude::*;
766     use net::*;
767     use net::test::{next_test_ip4, next_test_ip6};
768     use sync::mpsc::channel;
769     use sys_common::AsInner;
770     use time::{Instant, Duration};
771     use thread;
772
773     fn each_ip(f: &mut FnMut(SocketAddr)) {
774         f(next_test_ip4());
775         f(next_test_ip6());
776     }
777
778     macro_rules! t {
779         ($e:expr) => {
780             match $e {
781                 Ok(t) => t,
782                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
783             }
784         }
785     }
786
787     #[test]
788     fn bind_error() {
789         match TcpListener::bind("1.1.1.1:9999") {
790             Ok(..) => panic!(),
791             Err(e) =>
792                 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
793         }
794     }
795
796     #[test]
797     fn connect_error() {
798         match TcpStream::connect("0.0.0.0:1") {
799             Ok(..) => panic!(),
800             Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
801                               e.kind() == ErrorKind::InvalidInput ||
802                               e.kind() == ErrorKind::AddrInUse ||
803                               e.kind() == ErrorKind::AddrNotAvailable,
804                               "bad error: {} {:?}", e, e.kind()),
805         }
806     }
807
808     #[test]
809     fn listen_localhost() {
810         let socket_addr = next_test_ip4();
811         let listener = t!(TcpListener::bind(&socket_addr));
812
813         let _t = thread::spawn(move || {
814             let mut stream = t!(TcpStream::connect(&("localhost",
815                                                      socket_addr.port())));
816             t!(stream.write(&[144]));
817         });
818
819         let mut stream = t!(listener.accept()).0;
820         let mut buf = [0];
821         t!(stream.read(&mut buf));
822         assert!(buf[0] == 144);
823     }
824
825     #[test]
826     fn connect_loopback() {
827         each_ip(&mut |addr| {
828             let acceptor = t!(TcpListener::bind(&addr));
829
830             let _t = thread::spawn(move|| {
831                 let host = match addr {
832                     SocketAddr::V4(..) => "127.0.0.1",
833                     SocketAddr::V6(..) => "::1",
834                 };
835                 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
836                 t!(stream.write(&[66]));
837             });
838
839             let mut stream = t!(acceptor.accept()).0;
840             let mut buf = [0];
841             t!(stream.read(&mut buf));
842             assert!(buf[0] == 66);
843         })
844     }
845
846     #[test]
847     fn smoke_test() {
848         each_ip(&mut |addr| {
849             let acceptor = t!(TcpListener::bind(&addr));
850
851             let (tx, rx) = channel();
852             let _t = thread::spawn(move|| {
853                 let mut stream = t!(TcpStream::connect(&addr));
854                 t!(stream.write(&[99]));
855                 tx.send(t!(stream.local_addr())).unwrap();
856             });
857
858             let (mut stream, addr) = t!(acceptor.accept());
859             let mut buf = [0];
860             t!(stream.read(&mut buf));
861             assert!(buf[0] == 99);
862             assert_eq!(addr, t!(rx.recv()));
863         })
864     }
865
866     #[test]
867     fn read_eof() {
868         each_ip(&mut |addr| {
869             let acceptor = t!(TcpListener::bind(&addr));
870
871             let _t = thread::spawn(move|| {
872                 let _stream = t!(TcpStream::connect(&addr));
873                 // Close
874             });
875
876             let mut stream = t!(acceptor.accept()).0;
877             let mut buf = [0];
878             let nread = t!(stream.read(&mut buf));
879             assert_eq!(nread, 0);
880             let nread = t!(stream.read(&mut buf));
881             assert_eq!(nread, 0);
882         })
883     }
884
885     #[test]
886     fn write_close() {
887         each_ip(&mut |addr| {
888             let acceptor = t!(TcpListener::bind(&addr));
889
890             let (tx, rx) = channel();
891             let _t = thread::spawn(move|| {
892                 drop(t!(TcpStream::connect(&addr)));
893                 tx.send(()).unwrap();
894             });
895
896             let mut stream = t!(acceptor.accept()).0;
897             rx.recv().unwrap();
898             let buf = [0];
899             match stream.write(&buf) {
900                 Ok(..) => {}
901                 Err(e) => {
902                     assert!(e.kind() == ErrorKind::ConnectionReset ||
903                             e.kind() == ErrorKind::BrokenPipe ||
904                             e.kind() == ErrorKind::ConnectionAborted,
905                             "unknown error: {}", e);
906                 }
907             }
908         })
909     }
910
911     #[test]
912     fn multiple_connect_serial() {
913         each_ip(&mut |addr| {
914             let max = 10;
915             let acceptor = t!(TcpListener::bind(&addr));
916
917             let _t = thread::spawn(move|| {
918                 for _ in 0..max {
919                     let mut stream = t!(TcpStream::connect(&addr));
920                     t!(stream.write(&[99]));
921                 }
922             });
923
924             for stream in acceptor.incoming().take(max) {
925                 let mut stream = t!(stream);
926                 let mut buf = [0];
927                 t!(stream.read(&mut buf));
928                 assert_eq!(buf[0], 99);
929             }
930         })
931     }
932
933     #[test]
934     fn multiple_connect_interleaved_greedy_schedule() {
935         const MAX: usize = 10;
936         each_ip(&mut |addr| {
937             let acceptor = t!(TcpListener::bind(&addr));
938
939             let _t = thread::spawn(move|| {
940                 let acceptor = acceptor;
941                 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
942                     // Start another thread to handle the connection
943                     let _t = thread::spawn(move|| {
944                         let mut stream = t!(stream);
945                         let mut buf = [0];
946                         t!(stream.read(&mut buf));
947                         assert!(buf[0] == i as u8);
948                     });
949                 }
950             });
951
952             connect(0, addr);
953         });
954
955         fn connect(i: usize, addr: SocketAddr) {
956             if i == MAX { return }
957
958             let t = thread::spawn(move|| {
959                 let mut stream = t!(TcpStream::connect(&addr));
960                 // Connect again before writing
961                 connect(i + 1, addr);
962                 t!(stream.write(&[i as u8]));
963             });
964             t.join().ok().unwrap();
965         }
966     }
967
968     #[test]
969     fn multiple_connect_interleaved_lazy_schedule() {
970         const MAX: usize = 10;
971         each_ip(&mut |addr| {
972             let acceptor = t!(TcpListener::bind(&addr));
973
974             let _t = thread::spawn(move|| {
975                 for stream in acceptor.incoming().take(MAX) {
976                     // Start another thread to handle the connection
977                     let _t = thread::spawn(move|| {
978                         let mut stream = t!(stream);
979                         let mut buf = [0];
980                         t!(stream.read(&mut buf));
981                         assert!(buf[0] == 99);
982                     });
983                 }
984             });
985
986             connect(0, addr);
987         });
988
989         fn connect(i: usize, addr: SocketAddr) {
990             if i == MAX { return }
991
992             let t = thread::spawn(move|| {
993                 let mut stream = t!(TcpStream::connect(&addr));
994                 connect(i + 1, addr);
995                 t!(stream.write(&[99]));
996             });
997             t.join().ok().unwrap();
998         }
999     }
1000
1001     #[test]
1002     fn socket_and_peer_name() {
1003         each_ip(&mut |addr| {
1004             let listener = t!(TcpListener::bind(&addr));
1005             let so_name = t!(listener.local_addr());
1006             assert_eq!(addr, so_name);
1007             let _t = thread::spawn(move|| {
1008                 t!(listener.accept());
1009             });
1010
1011             let stream = t!(TcpStream::connect(&addr));
1012             assert_eq!(addr, t!(stream.peer_addr()));
1013         })
1014     }
1015
1016     #[test]
1017     fn partial_read() {
1018         each_ip(&mut |addr| {
1019             let (tx, rx) = channel();
1020             let srv = t!(TcpListener::bind(&addr));
1021             let _t = thread::spawn(move|| {
1022                 let mut cl = t!(srv.accept()).0;
1023                 cl.write(&[10]).unwrap();
1024                 let mut b = [0];
1025                 t!(cl.read(&mut b));
1026                 tx.send(()).unwrap();
1027             });
1028
1029             let mut c = t!(TcpStream::connect(&addr));
1030             let mut b = [0; 10];
1031             assert_eq!(c.read(&mut b).unwrap(), 1);
1032             t!(c.write(&[1]));
1033             rx.recv().unwrap();
1034         })
1035     }
1036
1037     #[test]
1038     fn double_bind() {
1039         each_ip(&mut |addr| {
1040             let _listener = t!(TcpListener::bind(&addr));
1041             match TcpListener::bind(&addr) {
1042                 Ok(..) => panic!(),
1043                 Err(e) => {
1044                     assert!(e.kind() == ErrorKind::ConnectionRefused ||
1045                             e.kind() == ErrorKind::Other ||
1046                             e.kind() == ErrorKind::AddrInUse,
1047                             "unknown error: {} {:?}", e, e.kind());
1048                 }
1049             }
1050         })
1051     }
1052
1053     #[test]
1054     fn fast_rebind() {
1055         each_ip(&mut |addr| {
1056             let acceptor = t!(TcpListener::bind(&addr));
1057
1058             let _t = thread::spawn(move|| {
1059                 t!(TcpStream::connect(&addr));
1060             });
1061
1062             t!(acceptor.accept());
1063             drop(acceptor);
1064             t!(TcpListener::bind(&addr));
1065         });
1066     }
1067
1068     #[test]
1069     fn tcp_clone_smoke() {
1070         each_ip(&mut |addr| {
1071             let acceptor = t!(TcpListener::bind(&addr));
1072
1073             let _t = thread::spawn(move|| {
1074                 let mut s = t!(TcpStream::connect(&addr));
1075                 let mut buf = [0, 0];
1076                 assert_eq!(s.read(&mut buf).unwrap(), 1);
1077                 assert_eq!(buf[0], 1);
1078                 t!(s.write(&[2]));
1079             });
1080
1081             let mut s1 = t!(acceptor.accept()).0;
1082             let s2 = t!(s1.try_clone());
1083
1084             let (tx1, rx1) = channel();
1085             let (tx2, rx2) = channel();
1086             let _t = thread::spawn(move|| {
1087                 let mut s2 = s2;
1088                 rx1.recv().unwrap();
1089                 t!(s2.write(&[1]));
1090                 tx2.send(()).unwrap();
1091             });
1092             tx1.send(()).unwrap();
1093             let mut buf = [0, 0];
1094             assert_eq!(s1.read(&mut buf).unwrap(), 1);
1095             rx2.recv().unwrap();
1096         })
1097     }
1098
1099     #[test]
1100     fn tcp_clone_two_read() {
1101         each_ip(&mut |addr| {
1102             let acceptor = t!(TcpListener::bind(&addr));
1103             let (tx1, rx) = channel();
1104             let tx2 = tx1.clone();
1105
1106             let _t = thread::spawn(move|| {
1107                 let mut s = t!(TcpStream::connect(&addr));
1108                 t!(s.write(&[1]));
1109                 rx.recv().unwrap();
1110                 t!(s.write(&[2]));
1111                 rx.recv().unwrap();
1112             });
1113
1114             let mut s1 = t!(acceptor.accept()).0;
1115             let s2 = t!(s1.try_clone());
1116
1117             let (done, rx) = channel();
1118             let _t = thread::spawn(move|| {
1119                 let mut s2 = s2;
1120                 let mut buf = [0, 0];
1121                 t!(s2.read(&mut buf));
1122                 tx2.send(()).unwrap();
1123                 done.send(()).unwrap();
1124             });
1125             let mut buf = [0, 0];
1126             t!(s1.read(&mut buf));
1127             tx1.send(()).unwrap();
1128
1129             rx.recv().unwrap();
1130         })
1131     }
1132
1133     #[test]
1134     fn tcp_clone_two_write() {
1135         each_ip(&mut |addr| {
1136             let acceptor = t!(TcpListener::bind(&addr));
1137
1138             let _t = thread::spawn(move|| {
1139                 let mut s = t!(TcpStream::connect(&addr));
1140                 let mut buf = [0, 1];
1141                 t!(s.read(&mut buf));
1142                 t!(s.read(&mut buf));
1143             });
1144
1145             let mut s1 = t!(acceptor.accept()).0;
1146             let s2 = t!(s1.try_clone());
1147
1148             let (done, rx) = channel();
1149             let _t = thread::spawn(move|| {
1150                 let mut s2 = s2;
1151                 t!(s2.write(&[1]));
1152                 done.send(()).unwrap();
1153             });
1154             t!(s1.write(&[2]));
1155
1156             rx.recv().unwrap();
1157         })
1158     }
1159
1160     #[test]
1161     fn shutdown_smoke() {
1162         each_ip(&mut |addr| {
1163             let a = t!(TcpListener::bind(&addr));
1164             let _t = thread::spawn(move|| {
1165                 let mut c = t!(a.accept()).0;
1166                 let mut b = [0];
1167                 assert_eq!(c.read(&mut b).unwrap(), 0);
1168                 t!(c.write(&[1]));
1169             });
1170
1171             let mut s = t!(TcpStream::connect(&addr));
1172             t!(s.shutdown(Shutdown::Write));
1173             assert!(s.write(&[1]).is_err());
1174             let mut b = [0, 0];
1175             assert_eq!(t!(s.read(&mut b)), 1);
1176             assert_eq!(b[0], 1);
1177         })
1178     }
1179
1180     #[test]
1181     fn close_readwrite_smoke() {
1182         each_ip(&mut |addr| {
1183             let a = t!(TcpListener::bind(&addr));
1184             let (tx, rx) = channel::<()>();
1185             let _t = thread::spawn(move|| {
1186                 let _s = t!(a.accept());
1187                 let _ = rx.recv();
1188             });
1189
1190             let mut b = [0];
1191             let mut s = t!(TcpStream::connect(&addr));
1192             let mut s2 = t!(s.try_clone());
1193
1194             // closing should prevent reads/writes
1195             t!(s.shutdown(Shutdown::Write));
1196             assert!(s.write(&[0]).is_err());
1197             t!(s.shutdown(Shutdown::Read));
1198             assert_eq!(s.read(&mut b).unwrap(), 0);
1199
1200             // closing should affect previous handles
1201             assert!(s2.write(&[0]).is_err());
1202             assert_eq!(s2.read(&mut b).unwrap(), 0);
1203
1204             // closing should affect new handles
1205             let mut s3 = t!(s.try_clone());
1206             assert!(s3.write(&[0]).is_err());
1207             assert_eq!(s3.read(&mut b).unwrap(), 0);
1208
1209             // make sure these don't die
1210             let _ = s2.shutdown(Shutdown::Read);
1211             let _ = s2.shutdown(Shutdown::Write);
1212             let _ = s3.shutdown(Shutdown::Read);
1213             let _ = s3.shutdown(Shutdown::Write);
1214             drop(tx);
1215         })
1216     }
1217
1218     #[test]
1219     #[cfg(unix)] // test doesn't work on Windows, see #31657
1220     fn close_read_wakes_up() {
1221         each_ip(&mut |addr| {
1222             let a = t!(TcpListener::bind(&addr));
1223             let (tx1, rx) = channel::<()>();
1224             let _t = thread::spawn(move|| {
1225                 let _s = t!(a.accept());
1226                 let _ = rx.recv();
1227             });
1228
1229             let s = t!(TcpStream::connect(&addr));
1230             let s2 = t!(s.try_clone());
1231             let (tx, rx) = channel();
1232             let _t = thread::spawn(move|| {
1233                 let mut s2 = s2;
1234                 assert_eq!(t!(s2.read(&mut [0])), 0);
1235                 tx.send(()).unwrap();
1236             });
1237             // this should wake up the child thread
1238             t!(s.shutdown(Shutdown::Read));
1239
1240             // this test will never finish if the child doesn't wake up
1241             rx.recv().unwrap();
1242             drop(tx1);
1243         })
1244     }
1245
1246     #[test]
1247     fn clone_while_reading() {
1248         each_ip(&mut |addr| {
1249             let accept = t!(TcpListener::bind(&addr));
1250
1251             // Enqueue a thread to write to a socket
1252             let (tx, rx) = channel();
1253             let (txdone, rxdone) = channel();
1254             let txdone2 = txdone.clone();
1255             let _t = thread::spawn(move|| {
1256                 let mut tcp = t!(TcpStream::connect(&addr));
1257                 rx.recv().unwrap();
1258                 t!(tcp.write(&[0]));
1259                 txdone2.send(()).unwrap();
1260             });
1261
1262             // Spawn off a reading clone
1263             let tcp = t!(accept.accept()).0;
1264             let tcp2 = t!(tcp.try_clone());
1265             let txdone3 = txdone.clone();
1266             let _t = thread::spawn(move|| {
1267                 let mut tcp2 = tcp2;
1268                 t!(tcp2.read(&mut [0]));
1269                 txdone3.send(()).unwrap();
1270             });
1271
1272             // Try to ensure that the reading clone is indeed reading
1273             for _ in 0..50 {
1274                 thread::yield_now();
1275             }
1276
1277             // clone the handle again while it's reading, then let it finish the
1278             // read.
1279             let _ = t!(tcp.try_clone());
1280             tx.send(()).unwrap();
1281             rxdone.recv().unwrap();
1282             rxdone.recv().unwrap();
1283         })
1284     }
1285
1286     #[test]
1287     fn clone_accept_smoke() {
1288         each_ip(&mut |addr| {
1289             let a = t!(TcpListener::bind(&addr));
1290             let a2 = t!(a.try_clone());
1291
1292             let _t = thread::spawn(move|| {
1293                 let _ = TcpStream::connect(&addr);
1294             });
1295             let _t = thread::spawn(move|| {
1296                 let _ = TcpStream::connect(&addr);
1297             });
1298
1299             t!(a.accept());
1300             t!(a2.accept());
1301         })
1302     }
1303
1304     #[test]
1305     fn clone_accept_concurrent() {
1306         each_ip(&mut |addr| {
1307             let a = t!(TcpListener::bind(&addr));
1308             let a2 = t!(a.try_clone());
1309
1310             let (tx, rx) = channel();
1311             let tx2 = tx.clone();
1312
1313             let _t = thread::spawn(move|| {
1314                 tx.send(t!(a.accept())).unwrap();
1315             });
1316             let _t = thread::spawn(move|| {
1317                 tx2.send(t!(a2.accept())).unwrap();
1318             });
1319
1320             let _t = thread::spawn(move|| {
1321                 let _ = TcpStream::connect(&addr);
1322             });
1323             let _t = thread::spawn(move|| {
1324                 let _ = TcpStream::connect(&addr);
1325             });
1326
1327             rx.recv().unwrap();
1328             rx.recv().unwrap();
1329         })
1330     }
1331
1332     #[test]
1333     fn debug() {
1334         let name = if cfg!(windows) {"socket"} else {"fd"};
1335         let socket_addr = next_test_ip4();
1336
1337         let listener = t!(TcpListener::bind(&socket_addr));
1338         let listener_inner = listener.0.socket().as_inner();
1339         let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1340                               socket_addr, name, listener_inner);
1341         assert_eq!(format!("{:?}", listener), compare);
1342
1343         let stream = t!(TcpStream::connect(&("localhost",
1344                                                  socket_addr.port())));
1345         let stream_inner = stream.0.socket().as_inner();
1346         let compare = format!("TcpStream {{ addr: {:?}, \
1347                               peer: {:?}, {}: {:?} }}",
1348                               stream.local_addr().unwrap(),
1349                               stream.peer_addr().unwrap(),
1350                               name,
1351                               stream_inner);
1352         assert_eq!(format!("{:?}", stream), compare);
1353     }
1354
1355     // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1356     //        no longer has rounding errors.
1357     #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1358     #[test]
1359     fn timeouts() {
1360         let addr = next_test_ip4();
1361         let listener = t!(TcpListener::bind(&addr));
1362
1363         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1364         let dur = Duration::new(15410, 0);
1365
1366         assert_eq!(None, t!(stream.read_timeout()));
1367
1368         t!(stream.set_read_timeout(Some(dur)));
1369         assert_eq!(Some(dur), t!(stream.read_timeout()));
1370
1371         assert_eq!(None, t!(stream.write_timeout()));
1372
1373         t!(stream.set_write_timeout(Some(dur)));
1374         assert_eq!(Some(dur), t!(stream.write_timeout()));
1375
1376         t!(stream.set_read_timeout(None));
1377         assert_eq!(None, t!(stream.read_timeout()));
1378
1379         t!(stream.set_write_timeout(None));
1380         assert_eq!(None, t!(stream.write_timeout()));
1381         drop(listener);
1382     }
1383
1384     #[test]
1385     fn test_read_timeout() {
1386         let addr = next_test_ip4();
1387         let listener = t!(TcpListener::bind(&addr));
1388
1389         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1390         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1391
1392         let mut buf = [0; 10];
1393         let start = Instant::now();
1394         let kind = stream.read(&mut buf).err().expect("expected error").kind();
1395         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1396         assert!(start.elapsed() > Duration::from_millis(400));
1397         drop(listener);
1398     }
1399
1400     #[test]
1401     fn test_read_with_timeout() {
1402         let addr = next_test_ip4();
1403         let listener = t!(TcpListener::bind(&addr));
1404
1405         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1406         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1407
1408         let mut other_end = t!(listener.accept()).0;
1409         t!(other_end.write_all(b"hello world"));
1410
1411         let mut buf = [0; 11];
1412         t!(stream.read(&mut buf));
1413         assert_eq!(b"hello world", &buf[..]);
1414
1415         let start = Instant::now();
1416         let kind = stream.read(&mut buf).err().expect("expected error").kind();
1417         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1418         assert!(start.elapsed() > Duration::from_millis(400));
1419         drop(listener);
1420     }
1421
1422     #[test]
1423     fn nodelay() {
1424         let addr = next_test_ip4();
1425         let _listener = t!(TcpListener::bind(&addr));
1426
1427         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1428
1429         assert_eq!(false, t!(stream.nodelay()));
1430         t!(stream.set_nodelay(true));
1431         assert_eq!(true, t!(stream.nodelay()));
1432         t!(stream.set_nodelay(false));
1433         assert_eq!(false, t!(stream.nodelay()));
1434     }
1435
1436     #[test]
1437     fn ttl() {
1438         let ttl = 100;
1439
1440         let addr = next_test_ip4();
1441         let listener = t!(TcpListener::bind(&addr));
1442
1443         t!(listener.set_ttl(ttl));
1444         assert_eq!(ttl, t!(listener.ttl()));
1445
1446         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1447
1448         t!(stream.set_ttl(ttl));
1449         assert_eq!(ttl, t!(stream.ttl()));
1450     }
1451
1452     #[test]
1453     fn set_nonblocking() {
1454         let addr = next_test_ip4();
1455         let listener = t!(TcpListener::bind(&addr));
1456
1457         t!(listener.set_nonblocking(true));
1458         t!(listener.set_nonblocking(false));
1459
1460         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1461
1462         t!(stream.set_nonblocking(false));
1463         t!(stream.set_nonblocking(true));
1464
1465         let mut buf = [0];
1466         match stream.read(&mut buf) {
1467             Ok(_) => panic!("expected error"),
1468             Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1469             Err(e) => panic!("unexpected error {}", e),
1470         }
1471     }
1472
1473     #[test]
1474     fn peek() {
1475         each_ip(&mut |addr| {
1476             let (txdone, rxdone) = channel();
1477
1478             let srv = t!(TcpListener::bind(&addr));
1479             let _t = thread::spawn(move|| {
1480                 let mut cl = t!(srv.accept()).0;
1481                 cl.write(&[1,3,3,7]).unwrap();
1482                 t!(rxdone.recv());
1483             });
1484
1485             let mut c = t!(TcpStream::connect(&addr));
1486             let mut b = [0; 10];
1487             for _ in 1..3 {
1488                 let len = c.peek(&mut b).unwrap();
1489                 assert_eq!(len, 4);
1490             }
1491             let len = c.read(&mut b).unwrap();
1492             assert_eq!(len, 4);
1493
1494             t!(c.set_nonblocking(true));
1495             match c.peek(&mut b) {
1496                 Ok(_) => panic!("expected error"),
1497                 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1498                 Err(e) => panic!("unexpected error {}", e),
1499             }
1500             t!(txdone.send(()));
1501         })
1502     }
1503 }