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