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