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