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