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