]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/tcp.rs
Update std::net:Incoming's docs to use standard iterator boilerplate
[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 iterator that infinitely [`accept`]s connections on a [`TcpListener`].
69 ///
70 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
71 /// See its documentation for more.
72 ///
73 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
74 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
75 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
76 #[stable(feature = "rust1", since = "1.0.0")]
77 #[derive(Debug)]
78 pub struct Incoming<'a> { listener: &'a TcpListener }
79
80 impl TcpStream {
81     /// Opens a TCP connection to a remote host.
82     ///
83     /// `addr` is an address of the remote host. Anything which implements
84     /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
85     /// documentation for concrete examples.
86     /// In case [`ToSocketAddrs::to_socket_addrs()`] returns more than one entry,
87     /// then the first valid and reachable address is used.
88     ///
89     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
90     /// [`ToSocketAddrs::to_socket_addrs()`]:
91     /// ../../std/net/trait.ToSocketAddrs.html#tymethod.to_socket_addrs
92     ///
93     /// # Examples
94     ///
95     /// ```no_run
96     /// use std::net::TcpStream;
97     ///
98     /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
99     ///     println!("Connected to the server!");
100     /// } else {
101     ///     println!("Couldn't connect to server...");
102     /// }
103     /// ```
104     #[stable(feature = "rust1", since = "1.0.0")]
105     pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
106         super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
107     }
108
109     /// Returns the socket address of the remote peer of this TCP connection.
110     ///
111     /// # Examples
112     ///
113     /// ```no_run
114     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
115     ///
116     /// let stream = TcpStream::connect("127.0.0.1:8080")
117     ///                        .expect("Couldn't connect to the server...");
118     /// assert_eq!(stream.peer_addr().unwrap(),
119     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
120     /// ```
121     #[stable(feature = "rust1", since = "1.0.0")]
122     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
123         self.0.peer_addr()
124     }
125
126     /// Returns the socket address of the local half of this TCP connection.
127     ///
128     /// # Examples
129     ///
130     /// ```no_run
131     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
132     ///
133     /// let stream = TcpStream::connect("127.0.0.1:8080")
134     ///                        .expect("Couldn't connect to the server...");
135     /// assert_eq!(stream.local_addr().unwrap(),
136     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
137     /// ```
138     #[stable(feature = "rust1", since = "1.0.0")]
139     pub fn local_addr(&self) -> io::Result<SocketAddr> {
140         self.0.socket_addr()
141     }
142
143     /// Shuts down the read, write, or both halves of this connection.
144     ///
145     /// This function will cause all pending and future I/O on the specified
146     /// portions to return immediately with an appropriate value (see the
147     /// documentation of [`Shutdown`]).
148     ///
149     /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
150     ///
151     /// # Examples
152     ///
153     /// ```no_run
154     /// use std::net::{Shutdown, TcpStream};
155     ///
156     /// let stream = TcpStream::connect("127.0.0.1:8080")
157     ///                        .expect("Couldn't connect to the server...");
158     /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
159     /// ```
160     #[stable(feature = "rust1", since = "1.0.0")]
161     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
162         self.0.shutdown(how)
163     }
164
165     /// Creates a new independently owned handle to the underlying socket.
166     ///
167     /// The returned `TcpStream` is a reference to the same stream that this
168     /// object references. Both handles will read and write the same stream of
169     /// data, and options set on one stream will be propagated to the other
170     /// stream.
171     ///
172     /// # Examples
173     ///
174     /// ```no_run
175     /// use std::net::TcpStream;
176     ///
177     /// let stream = TcpStream::connect("127.0.0.1:8080")
178     ///                        .expect("Couldn't connect to the server...");
179     /// let stream_clone = stream.try_clone().expect("clone failed...");
180     /// ```
181     #[stable(feature = "rust1", since = "1.0.0")]
182     pub fn try_clone(&self) -> io::Result<TcpStream> {
183         self.0.duplicate().map(TcpStream)
184     }
185
186     /// Sets the read timeout to the timeout specified.
187     ///
188     /// If the value specified is [`None`], then [`read`] calls will block
189     /// indefinitely. It is an error to pass the zero `Duration` to this
190     /// method.
191     ///
192     /// # Note
193     ///
194     /// Platforms may return a different error code whenever a read times out as
195     /// a result of setting this option. For example Unix typically returns an
196     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
197     ///
198     /// [`None`]: ../../std/option/enum.Option.html#variant.None
199     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
200     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
201     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
202     ///
203     /// # Examples
204     ///
205     /// ```no_run
206     /// use std::net::TcpStream;
207     ///
208     /// let stream = TcpStream::connect("127.0.0.1:8080")
209     ///                        .expect("Couldn't connect to the server...");
210     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
211     /// ```
212     #[stable(feature = "socket_timeout", since = "1.4.0")]
213     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
214         self.0.set_read_timeout(dur)
215     }
216
217     /// Sets the write timeout to the timeout specified.
218     ///
219     /// If the value specified is [`None`], then [`write`] calls will block
220     /// indefinitely. It is an error to pass the zero [`Duration`] to this
221     /// method.
222     ///
223     /// # Note
224     ///
225     /// Platforms may return a different error code whenever a write times out
226     /// as a result of setting this option. For example Unix typically returns
227     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
228     ///
229     /// [`None`]: ../../std/option/enum.Option.html#variant.None
230     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
231     /// [`Duration`]: ../../std/time/struct.Duration.html
232     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
233     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
234     ///
235     /// # Examples
236     ///
237     /// ```no_run
238     /// use std::net::TcpStream;
239     ///
240     /// let stream = TcpStream::connect("127.0.0.1:8080")
241     ///                        .expect("Couldn't connect to the server...");
242     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
243     /// ```
244     #[stable(feature = "socket_timeout", since = "1.4.0")]
245     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
246         self.0.set_write_timeout(dur)
247     }
248
249     /// Returns the read timeout of this socket.
250     ///
251     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
252     ///
253     /// # Note
254     ///
255     /// Some platforms do not provide access to the current timeout.
256     ///
257     /// [`None`]: ../../std/option/enum.Option.html#variant.None
258     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
259     ///
260     /// # Examples
261     ///
262     /// ```no_run
263     /// use std::net::TcpStream;
264     ///
265     /// let stream = TcpStream::connect("127.0.0.1:8080")
266     ///                        .expect("Couldn't connect to the server...");
267     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
268     /// assert_eq!(stream.read_timeout().unwrap(), None);
269     /// ```
270     #[stable(feature = "socket_timeout", since = "1.4.0")]
271     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
272         self.0.read_timeout()
273     }
274
275     /// Returns the write timeout of this socket.
276     ///
277     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
278     ///
279     /// # Note
280     ///
281     /// Some platforms do not provide access to the current timeout.
282     ///
283     /// [`None`]: ../../std/option/enum.Option.html#variant.None
284     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
285     ///
286     /// # Examples
287     ///
288     /// ```no_run
289     /// use std::net::TcpStream;
290     ///
291     /// let stream = TcpStream::connect("127.0.0.1:8080")
292     ///                        .expect("Couldn't connect to the server...");
293     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
294     /// assert_eq!(stream.write_timeout().unwrap(), None);
295     /// ```
296     #[stable(feature = "socket_timeout", since = "1.4.0")]
297     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
298         self.0.write_timeout()
299     }
300
301     /// Receives data on the socket from the remote adress to which it is
302     /// connected, without removing that data from the queue. On success,
303     /// returns the number of bytes peeked.
304     ///
305     /// Successive calls return the same data. This is accomplished by passing
306     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
307     ///
308     /// # Examples
309     ///
310     /// ```no_run
311     /// #![feature(peek)]
312     /// use std::net::TcpStream;
313     ///
314     /// let stream = TcpStream::connect("127.0.0.1:8000")
315     ///                        .expect("couldn't bind to address");
316     /// let mut buf = [0; 10];
317     /// let len = stream.peek(&mut buf).expect("peek failed");
318     /// ```
319     #[unstable(feature = "peek", issue = "38980")]
320     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
321         self.0.peek(buf)
322     }
323
324     /// Sets the value of the `TCP_NODELAY` option on this socket.
325     ///
326     /// If set, this option disables the Nagle algorithm. This means that
327     /// segments are always sent as soon as possible, even if there is only a
328     /// small amount of data. When not set, data is buffered until there is a
329     /// sufficient amount to send out, thereby avoiding the frequent sending of
330     /// small packets.
331     ///
332     /// # Examples
333     ///
334     /// ```no_run
335     /// use std::net::TcpStream;
336     ///
337     /// let stream = TcpStream::connect("127.0.0.1:8080")
338     ///                        .expect("Couldn't connect to the server...");
339     /// stream.set_nodelay(true).expect("set_nodelay call failed");
340     /// ```
341     #[stable(feature = "net2_mutators", since = "1.9.0")]
342     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
343         self.0.set_nodelay(nodelay)
344     }
345
346     /// Gets the value of the `TCP_NODELAY` option on this socket.
347     ///
348     /// For more information about this option, see [`set_nodelay`][link].
349     ///
350     /// [link]: #method.set_nodelay
351     ///
352     /// # Examples
353     ///
354     /// ```no_run
355     /// use std::net::TcpStream;
356     ///
357     /// let stream = TcpStream::connect("127.0.0.1:8080")
358     ///                        .expect("Couldn't connect to the server...");
359     /// stream.set_nodelay(true).expect("set_nodelay call failed");
360     /// assert_eq!(stream.nodelay().unwrap_or(false), true);
361     /// ```
362     #[stable(feature = "net2_mutators", since = "1.9.0")]
363     pub fn nodelay(&self) -> io::Result<bool> {
364         self.0.nodelay()
365     }
366
367     /// Sets the value for the `IP_TTL` option on this socket.
368     ///
369     /// This value sets the time-to-live field that is used in every packet sent
370     /// from this socket.
371     ///
372     /// # Examples
373     ///
374     /// ```no_run
375     /// use std::net::TcpStream;
376     ///
377     /// let stream = TcpStream::connect("127.0.0.1:8080")
378     ///                        .expect("Couldn't connect to the server...");
379     /// stream.set_ttl(100).expect("set_ttl call failed");
380     /// ```
381     #[stable(feature = "net2_mutators", since = "1.9.0")]
382     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
383         self.0.set_ttl(ttl)
384     }
385
386     /// Gets the value of the `IP_TTL` option for this socket.
387     ///
388     /// For more information about this option, see [`set_ttl`][link].
389     ///
390     /// [link]: #method.set_ttl
391     ///
392     /// # Examples
393     ///
394     /// ```no_run
395     /// use std::net::TcpStream;
396     ///
397     /// let stream = TcpStream::connect("127.0.0.1:8080")
398     ///                        .expect("Couldn't connect to the server...");
399     /// stream.set_ttl(100).expect("set_ttl call failed");
400     /// assert_eq!(stream.ttl().unwrap_or(0), 100);
401     /// ```
402     #[stable(feature = "net2_mutators", since = "1.9.0")]
403     pub fn ttl(&self) -> io::Result<u32> {
404         self.0.ttl()
405     }
406
407     /// Get the value of the `SO_ERROR` option on this socket.
408     ///
409     /// This will retrieve the stored error in the underlying socket, clearing
410     /// the field in the process. This can be useful for checking errors between
411     /// calls.
412     ///
413     /// # Examples
414     ///
415     /// ```no_run
416     /// use std::net::TcpStream;
417     ///
418     /// let stream = TcpStream::connect("127.0.0.1:8080")
419     ///                        .expect("Couldn't connect to the server...");
420     /// stream.take_error().expect("No error was expected...");
421     /// ```
422     #[stable(feature = "net2_mutators", since = "1.9.0")]
423     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
424         self.0.take_error()
425     }
426
427     /// Moves this TCP stream into or out of nonblocking mode.
428     ///
429     /// On Unix this corresponds to calling fcntl, and on Windows this
430     /// corresponds to calling ioctlsocket.
431     ///
432     /// # Examples
433     ///
434     /// ```no_run
435     /// use std::net::TcpStream;
436     ///
437     /// let stream = TcpStream::connect("127.0.0.1:8080")
438     ///                        .expect("Couldn't connect to the server...");
439     /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
440     /// ```
441     #[stable(feature = "net2_mutators", since = "1.9.0")]
442     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
443         self.0.set_nonblocking(nonblocking)
444     }
445 }
446
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl Read for TcpStream {
449     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
450     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
451         self.0.read_to_end(buf)
452     }
453 }
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl Write for TcpStream {
456     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
457     fn flush(&mut self) -> io::Result<()> { Ok(()) }
458 }
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl<'a> Read for &'a TcpStream {
461     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
462     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
463         self.0.read_to_end(buf)
464     }
465 }
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl<'a> Write for &'a TcpStream {
468     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
469     fn flush(&mut self) -> io::Result<()> { Ok(()) }
470 }
471
472 impl AsInner<net_imp::TcpStream> for TcpStream {
473     fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
474 }
475
476 impl FromInner<net_imp::TcpStream> for TcpStream {
477     fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
478 }
479
480 impl IntoInner<net_imp::TcpStream> for TcpStream {
481     fn into_inner(self) -> net_imp::TcpStream { self.0 }
482 }
483
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl fmt::Debug for TcpStream {
486     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
487         self.0.fmt(f)
488     }
489 }
490
491 impl TcpListener {
492     /// Creates a new `TcpListener` which will be bound to the specified
493     /// address.
494     ///
495     /// The returned listener is ready for accepting connections.
496     ///
497     /// Binding with a port number of 0 will request that the OS assigns a port
498     /// to this listener. The port allocated can be queried via the
499     /// [`local_addr`] method.
500     ///
501     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
502     /// its documentation for concrete examples.
503     ///
504     /// [`local_addr`]: #method.local_addr
505     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
506     ///
507     /// # Examples
508     ///
509     /// ```no_run
510     /// use std::net::TcpListener;
511     ///
512     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
513     /// ```
514     #[stable(feature = "rust1", since = "1.0.0")]
515     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
516         super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
517     }
518
519     /// Returns the local socket address of this listener.
520     ///
521     /// # Examples
522     ///
523     /// ```no_run
524     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
525     ///
526     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
527     /// assert_eq!(listener.local_addr().unwrap(),
528     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
529     /// ```
530     #[stable(feature = "rust1", since = "1.0.0")]
531     pub fn local_addr(&self) -> io::Result<SocketAddr> {
532         self.0.socket_addr()
533     }
534
535     /// Creates a new independently owned handle to the underlying socket.
536     ///
537     /// The returned [`TcpListener`] is a reference to the same socket that this
538     /// object references. Both handles can be used to accept incoming
539     /// connections and options set on one listener will affect the other.
540     ///
541     /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
542     ///
543     /// # Examples
544     ///
545     /// ```no_run
546     /// use std::net::TcpListener;
547     ///
548     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
549     /// let listener_clone = listener.try_clone().unwrap();
550     /// ```
551     #[stable(feature = "rust1", since = "1.0.0")]
552     pub fn try_clone(&self) -> io::Result<TcpListener> {
553         self.0.duplicate().map(TcpListener)
554     }
555
556     /// Accept a new incoming connection from this listener.
557     ///
558     /// This function will block the calling thread until a new TCP connection
559     /// is established. When established, the corresponding [`TcpStream`] and the
560     /// remote peer's address will be returned.
561     ///
562     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
563     ///
564     /// # Examples
565     ///
566     /// ```no_run
567     /// use std::net::TcpListener;
568     ///
569     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
570     /// match listener.accept() {
571     ///     Ok((_socket, addr)) => println!("new client: {:?}", addr),
572     ///     Err(e) => println!("couldn't get client: {:?}", e),
573     /// }
574     /// ```
575     #[stable(feature = "rust1", since = "1.0.0")]
576     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
577         self.0.accept().map(|(a, b)| (TcpStream(a), b))
578     }
579
580     /// Returns an iterator over the connections being received on this
581     /// listener.
582     ///
583     /// The returned iterator will never return [`None`] and will also not yield
584     /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
585     /// calling [`accept`] in a loop.
586     ///
587     /// [`None`]: ../../std/option/enum.Option.html#variant.None
588     /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
589     /// [`accept`]: #method.accept
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 }