Skip to main content

std/net/
tcp.rs

1#![deny(unsafe_op_in_unsafe_fn)]
2
3#[cfg(all(
4    test,
5    not(any(
6        target_os = "emscripten",
7        all(target_os = "wasi", target_env = "p1"),
8        target_os = "xous",
9        target_os = "trusty",
10        target_os = "l4re",
11    ))
12))]
13mod tests;
14
15use crate::fmt;
16use crate::io::prelude::*;
17use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut};
18use crate::iter::FusedIterator;
19use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
20use crate::sys::{AsInner, FromInner, IntoInner, net as net_imp};
21use crate::time::Duration;
22
23/// A TCP stream between a local and a remote socket.
24///
25/// After creating a `TcpStream` by either [`connect`]ing to a remote host or
26/// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
27/// by [reading] and [writing] to it.
28///
29/// The connection will be closed when the value is dropped. The reading and writing
30/// portions of the connection can also be shut down individually with the [`shutdown`]
31/// method.
32///
33/// The Transmission Control Protocol is specified in [IETF RFC 793].
34///
35/// [`accept`]: TcpListener::accept
36/// [`connect`]: TcpStream::connect
37/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
38/// [reading]: Read
39/// [`shutdown`]: TcpStream::shutdown
40/// [writing]: Write
41///
42/// # Examples
43///
44/// ```no_run
45/// use std::io::prelude::*;
46/// use std::net::TcpStream;
47///
48/// fn main() -> std::io::Result<()> {
49///     let mut stream = TcpStream::connect("127.0.0.1:34254")?;
50///
51///     stream.write(&[1])?;
52///     stream.read(&mut [0; 128])?;
53///     Ok(())
54/// } // the stream is closed here
55/// ```
56///
57/// # Platform-specific Behavior
58///
59/// On Unix, writes to the underlying socket in `SOCK_STREAM` mode are made with
60/// `MSG_NOSIGNAL` flag. This suppresses the emission of the  `SIGPIPE` signal when writing
61/// to disconnected socket. In some cases, getting a `SIGPIPE` would trigger process termination.
62#[stable(feature = "rust1", since = "1.0.0")]
63pub struct TcpStream(net_imp::TcpStream);
64
65/// A TCP socket server, listening for connections.
66///
67/// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
68/// for incoming TCP connections. These can be accepted by calling [`accept`] or by
69/// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
70///
71/// The socket will be closed when the value is dropped.
72///
73/// The Transmission Control Protocol is specified in [IETF RFC 793].
74///
75/// [`accept`]: TcpListener::accept
76/// [`bind`]: TcpListener::bind
77/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
78///
79/// # Examples
80///
81/// ```no_run
82/// use std::net::{TcpListener, TcpStream};
83///
84/// fn handle_client(stream: TcpStream) {
85///     // ...
86/// }
87///
88/// fn main() -> std::io::Result<()> {
89///     let listener = TcpListener::bind("127.0.0.1:80")?;
90///
91///     // accept connections and process them serially
92///     for stream in listener.incoming() {
93///         handle_client(stream?);
94///     }
95///     Ok(())
96/// }
97/// ```
98#[stable(feature = "rust1", since = "1.0.0")]
99pub struct TcpListener(net_imp::TcpListener);
100
101/// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
102///
103/// This `struct` is created by the [`TcpListener::incoming`] method.
104/// See its documentation for more.
105///
106/// [`accept`]: TcpListener::accept
107#[must_use = "iterators are lazy and do nothing unless consumed"]
108#[stable(feature = "rust1", since = "1.0.0")]
109#[derive(Debug)]
110pub struct Incoming<'a> {
111    listener: &'a TcpListener,
112}
113
114/// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
115///
116/// This `struct` is created by the [`TcpListener::into_incoming`] method.
117/// See its documentation for more.
118///
119/// [`accept`]: TcpListener::accept
120#[derive(Debug)]
121#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
122pub struct IntoIncoming {
123    listener: TcpListener,
124}
125
126impl TcpStream {
127    /// Opens a TCP connection to a remote host.
128    ///
129    /// `addr` is an address of the remote host. Anything which implements
130    /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
131    /// documentation for concrete examples.
132    ///
133    /// If `addr` yields multiple addresses, `connect` will be attempted with
134    /// each of the addresses until a connection is successful. If none of
135    /// the addresses result in a successful connection, the error returned from
136    /// the last connection attempt (the last address) is returned.
137    ///
138    /// # Examples
139    ///
140    /// Open a TCP connection to `127.0.0.1:8080`:
141    ///
142    /// ```no_run
143    /// use std::net::TcpStream;
144    ///
145    /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
146    ///     println!("Connected to the server!");
147    /// } else {
148    ///     println!("Couldn't connect to server...");
149    /// }
150    /// ```
151    ///
152    /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
153    /// a TCP connection to `127.0.0.1:8081`:
154    ///
155    /// ```no_run
156    /// use std::net::{SocketAddr, TcpStream};
157    ///
158    /// let addrs = [
159    ///     SocketAddr::from(([127, 0, 0, 1], 8080)),
160    ///     SocketAddr::from(([127, 0, 0, 1], 8081)),
161    /// ];
162    /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
163    ///     println!("Connected to the server!");
164    /// } else {
165    ///     println!("Couldn't connect to server...");
166    /// }
167    /// ```
168    #[stable(feature = "rust1", since = "1.0.0")]
169    pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
170        net_imp::TcpStream::connect(addr).map(TcpStream)
171    }
172
173    /// Opens a TCP connection to a remote host with a timeout.
174    ///
175    /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
176    /// timeout must be applied to individual addresses.
177    ///
178    /// It is an error to pass a zero `Duration` to this function.
179    ///
180    /// Unlike other methods on `TcpStream`, this does not correspond to a
181    /// single system call. It instead calls `connect` in nonblocking mode and
182    /// then uses an OS-specific mechanism to await the completion of the
183    /// connection request.
184    #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
185    pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
186        net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
187    }
188
189    /// Returns the socket address of the remote peer of this TCP connection.
190    ///
191    /// # Examples
192    ///
193    /// ```no_run
194    /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
195    ///
196    /// let stream = TcpStream::connect("127.0.0.1:8080")
197    ///                        .expect("Couldn't connect to the server...");
198    /// assert_eq!(stream.peer_addr().unwrap(),
199    ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
200    /// ```
201    #[stable(feature = "rust1", since = "1.0.0")]
202    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
203        self.0.peer_addr()
204    }
205
206    /// Returns the socket address of the local half of this TCP connection.
207    ///
208    /// # Examples
209    ///
210    /// ```no_run
211    /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
212    ///
213    /// let stream = TcpStream::connect("127.0.0.1:8080")
214    ///                        .expect("Couldn't connect to the server...");
215    /// assert_eq!(stream.local_addr().unwrap().ip(),
216    ///            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
217    /// ```
218    #[stable(feature = "rust1", since = "1.0.0")]
219    pub fn local_addr(&self) -> io::Result<SocketAddr> {
220        self.0.socket_addr()
221    }
222
223    /// Shuts down the read, write, or both halves of this connection.
224    ///
225    /// This function will cause all pending and future I/O on the specified
226    /// portions to return immediately with an appropriate value (see the
227    /// documentation of [`Shutdown`]).
228    ///
229    /// # Platform-specific behavior
230    ///
231    /// Calling this function multiple times may result in different behavior,
232    /// depending on the operating system. On Linux, the second call will
233    /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
234    /// This may change in the future.
235    ///
236    /// # Examples
237    ///
238    /// ```no_run
239    /// use std::net::{Shutdown, TcpStream};
240    ///
241    /// let stream = TcpStream::connect("127.0.0.1:8080")
242    ///                        .expect("Couldn't connect to the server...");
243    /// stream.shutdown(Shutdown::Both).expect("shutdown should succeed");
244    /// ```
245    #[stable(feature = "rust1", since = "1.0.0")]
246    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
247        self.0.shutdown(how)
248    }
249
250    /// Creates a new independently owned handle to the underlying socket.
251    ///
252    /// The returned `TcpStream` is a reference to the same stream that this
253    /// object references. Both handles will read and write the same stream of
254    /// data, and options set on one stream will be propagated to the other
255    /// stream.
256    ///
257    /// # Examples
258    ///
259    /// ```no_run
260    /// use std::net::TcpStream;
261    ///
262    /// let stream = TcpStream::connect("127.0.0.1:8080")
263    ///                        .expect("Couldn't connect to the server...");
264    /// let stream_clone = stream.try_clone().expect("clone should succeed");
265    /// ```
266    #[stable(feature = "rust1", since = "1.0.0")]
267    pub fn try_clone(&self) -> io::Result<TcpStream> {
268        self.0.duplicate().map(TcpStream)
269    }
270
271    /// Sets the read timeout to the timeout specified.
272    ///
273    /// If the value specified is [`None`], then [`read`] calls will block
274    /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
275    /// passed to this method.
276    ///
277    /// # Platform-specific behavior
278    ///
279    /// Platforms may return a different error code whenever a read times out as
280    /// a result of setting this option. For example Unix typically returns an
281    /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
282    ///
283    /// [`read`]: Read::read
284    /// [`WouldBlock`]: io::ErrorKind::WouldBlock
285    /// [`TimedOut`]: io::ErrorKind::TimedOut
286    ///
287    /// # Examples
288    ///
289    /// ```no_run
290    /// use std::net::TcpStream;
291    ///
292    /// let stream = TcpStream::connect("127.0.0.1:8080")
293    ///                        .expect("Couldn't connect to the server...");
294    /// stream.set_read_timeout(None).expect("set_read_timeout should succeed");
295    /// ```
296    ///
297    /// An [`Err`] is returned if the zero [`Duration`] is passed to this
298    /// method:
299    ///
300    /// ```no_run
301    /// use std::io;
302    /// use std::net::TcpStream;
303    /// use std::time::Duration;
304    ///
305    /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
306    /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
307    /// let err = result.unwrap_err();
308    /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
309    /// ```
310    #[stable(feature = "socket_timeout", since = "1.4.0")]
311    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
312        self.0.set_read_timeout(dur)
313    }
314
315    /// Sets the write timeout to the timeout specified.
316    ///
317    /// If the value specified is [`None`], then [`write`] calls will block
318    /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
319    /// passed to this method.
320    ///
321    /// # Platform-specific behavior
322    ///
323    /// Platforms may return a different error code whenever a write times out
324    /// as a result of setting this option. For example Unix typically returns
325    /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
326    ///
327    /// [`write`]: Write::write
328    /// [`WouldBlock`]: io::ErrorKind::WouldBlock
329    /// [`TimedOut`]: io::ErrorKind::TimedOut
330    ///
331    /// # Examples
332    ///
333    /// ```no_run
334    /// use std::net::TcpStream;
335    ///
336    /// let stream = TcpStream::connect("127.0.0.1:8080")
337    ///                        .expect("Couldn't connect to the server...");
338    /// stream.set_write_timeout(None).expect("set_write_timeout should succeed");
339    /// ```
340    ///
341    /// An [`Err`] is returned if the zero [`Duration`] is passed to this
342    /// method:
343    ///
344    /// ```no_run
345    /// use std::io;
346    /// use std::net::TcpStream;
347    /// use std::time::Duration;
348    ///
349    /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
350    /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
351    /// let err = result.unwrap_err();
352    /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
353    /// ```
354    #[stable(feature = "socket_timeout", since = "1.4.0")]
355    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
356        self.0.set_write_timeout(dur)
357    }
358
359    /// Returns the read timeout of this socket.
360    ///
361    /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
362    ///
363    /// # Platform-specific behavior
364    ///
365    /// Some platforms do not provide access to the current timeout.
366    ///
367    /// [`read`]: Read::read
368    ///
369    /// # Examples
370    ///
371    /// ```no_run
372    /// use std::net::TcpStream;
373    ///
374    /// let stream = TcpStream::connect("127.0.0.1:8080")
375    ///                        .expect("Couldn't connect to the server...");
376    /// stream.set_read_timeout(None).expect("set_read_timeout should succeed");
377    /// assert_eq!(stream.read_timeout().unwrap(), None);
378    /// ```
379    #[stable(feature = "socket_timeout", since = "1.4.0")]
380    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
381        self.0.read_timeout()
382    }
383
384    /// Returns the write timeout of this socket.
385    ///
386    /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
387    ///
388    /// # Platform-specific behavior
389    ///
390    /// Some platforms do not provide access to the current timeout.
391    ///
392    /// [`write`]: Write::write
393    ///
394    /// # Examples
395    ///
396    /// ```no_run
397    /// use std::net::TcpStream;
398    ///
399    /// let stream = TcpStream::connect("127.0.0.1:8080")
400    ///                        .expect("Couldn't connect to the server...");
401    /// stream.set_write_timeout(None).expect("set_write_timeout should succeed");
402    /// assert_eq!(stream.write_timeout().unwrap(), None);
403    /// ```
404    #[stable(feature = "socket_timeout", since = "1.4.0")]
405    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
406        self.0.write_timeout()
407    }
408
409    /// Receives data on the socket from the remote address to which it is
410    /// connected, without removing that data from the queue. On success,
411    /// returns the number of bytes peeked.
412    ///
413    /// Successive calls return the same data. This is accomplished by passing
414    /// `MSG_PEEK` as a flag to the underlying `recv` system call.
415    ///
416    /// # Examples
417    ///
418    /// ```no_run
419    /// use std::net::TcpStream;
420    ///
421    /// let stream = TcpStream::connect("127.0.0.1:8000")
422    ///                        .expect("Couldn't connect to the server...");
423    /// let mut buf = [0; 10];
424    /// let len = stream.peek(&mut buf).expect("peek should succeed");
425    /// ```
426    #[stable(feature = "peek", since = "1.18.0")]
427    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
428        self.0.peek(buf)
429    }
430
431    /// Sets the value of the `SO_LINGER` option on this socket.
432    ///
433    /// This value controls how the socket is closed when data remains
434    /// to be sent. If `SO_LINGER` is set, the socket will remain open
435    /// for the specified duration as the system attempts to send pending data.
436    /// Otherwise, the system may close the socket immediately, or wait for a
437    /// default timeout.
438    ///
439    /// # Examples
440    ///
441    /// ```no_run
442    /// #![feature(tcp_linger)]
443    ///
444    /// use std::net::TcpStream;
445    /// use std::time::Duration;
446    ///
447    /// let stream = TcpStream::connect("127.0.0.1:8080")
448    ///                        .expect("Couldn't connect to the server...");
449    /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger should succeed");
450    /// ```
451    #[unstable(feature = "tcp_linger", issue = "88494")]
452    pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
453        self.0.set_linger(linger)
454    }
455
456    /// Gets the value of the `SO_LINGER` option on this socket.
457    ///
458    /// For more information about this option, see [`TcpStream::set_linger`].
459    ///
460    /// # Examples
461    ///
462    /// ```no_run
463    /// #![feature(tcp_linger)]
464    ///
465    /// use std::net::TcpStream;
466    /// use std::time::Duration;
467    ///
468    /// let stream = TcpStream::connect("127.0.0.1:8080")
469    ///                        .expect("Couldn't connect to the server...");
470    /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger should succeed");
471    /// assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
472    /// ```
473    #[unstable(feature = "tcp_linger", issue = "88494")]
474    pub fn linger(&self) -> io::Result<Option<Duration>> {
475        self.0.linger()
476    }
477
478    /// Sets the value of the `SO_KEEPALIVE` option on this socket.
479    ///
480    /// If set to `true`, the operating system will periodically send keepalive
481    /// probes on an idle connection to verify that the remote peer is still
482    /// reachable. If the peer fails to respond after a system-determined number
483    /// of probes, the connection is considered broken and subsequent I/O calls
484    /// will return an error.
485    ///
486    /// This is useful for detecting dead peers on long-lived connections where
487    /// no application-level traffic is exchanged, such as database or SSH
488    /// connections.
489    ///
490    /// The timing and frequency of keepalive probes are controlled by
491    /// system-level settings and are not configured by this method alone.
492    ///
493    /// # Examples
494    ///
495    /// ```no_run
496    /// #![feature(tcp_keepalive)]
497    ///
498    /// use std::net::TcpStream;
499    ///
500    /// let stream = TcpStream::connect("127.0.0.1:8080")
501    ///                        .expect("Couldn't connect to the server...");
502    /// stream.set_keepalive(true).expect("set_keepalive should succeed");
503    #[unstable(feature = "tcp_keepalive", issue = "155889")]
504    pub fn set_keepalive(&self, keepalive: bool) -> io::Result<()> {
505        self.0.set_keepalive(keepalive)
506    }
507
508    /// Gets the value of the `SO_KEEPALIVE` option on this socket.
509    ///
510    /// For more information about this option, see [`TcpStream::set_keepalive`].
511    ///
512    /// # Examples
513    ///
514    /// ```no_run
515    /// #![feature(tcp_keepalive)]
516    ///
517    /// use std::net::TcpStream;
518    ///
519    /// let stream = TcpStream::connect("127.0.0.1:8080")
520    ///                        .expect("Couldn't connect to the server...");
521    /// stream.set_keepalive(true).expect("set_keepalive should succeed");
522    /// assert_eq!(stream.keepalive().unwrap_or(false), true);
523    /// ```
524    #[unstable(feature = "tcp_keepalive", issue = "155889")]
525    pub fn keepalive(&self) -> io::Result<bool> {
526        self.0.keepalive()
527    }
528
529    /// Sets the value of the `TCP_NODELAY` option on this socket.
530    ///
531    /// If set, this option disables the Nagle algorithm. This means that
532    /// segments are always sent as soon as possible, even if there is only a
533    /// small amount of data. When not set, data is buffered until there is a
534    /// sufficient amount to send out, thereby avoiding the frequent sending of
535    /// small packets.
536    ///
537    /// # Examples
538    ///
539    /// ```no_run
540    /// use std::net::TcpStream;
541    ///
542    /// let stream = TcpStream::connect("127.0.0.1:8080")
543    ///                        .expect("Couldn't connect to the server...");
544    /// stream.set_nodelay(true).expect("set_nodelay should succeed");
545    /// ```
546    #[stable(feature = "net2_mutators", since = "1.9.0")]
547    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
548        self.0.set_nodelay(nodelay)
549    }
550
551    /// Gets the value of the `TCP_NODELAY` option on this socket.
552    ///
553    /// For more information about this option, see [`TcpStream::set_nodelay`].
554    ///
555    /// # Examples
556    ///
557    /// ```no_run
558    /// use std::net::TcpStream;
559    ///
560    /// let stream = TcpStream::connect("127.0.0.1:8080")
561    ///                        .expect("Couldn't connect to the server...");
562    /// stream.set_nodelay(true).expect("set_nodelay should succeed");
563    /// assert_eq!(stream.nodelay().unwrap_or(false), true);
564    /// ```
565    #[stable(feature = "net2_mutators", since = "1.9.0")]
566    pub fn nodelay(&self) -> io::Result<bool> {
567        self.0.nodelay()
568    }
569
570    /// Sets the value for the `IP_TTL` option on this socket.
571    ///
572    /// This value sets the time-to-live field that is used in every packet sent
573    /// from this socket.
574    ///
575    /// # Examples
576    ///
577    /// ```no_run
578    /// use std::net::TcpStream;
579    ///
580    /// let stream = TcpStream::connect("127.0.0.1:8080")
581    ///                        .expect("Couldn't connect to the server...");
582    /// stream.set_ttl(100).expect("set_ttl should succeed");
583    /// ```
584    #[stable(feature = "net2_mutators", since = "1.9.0")]
585    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
586        self.0.set_ttl(ttl)
587    }
588
589    /// Gets the value of the `IP_TTL` option for this socket.
590    ///
591    /// For more information about this option, see [`TcpStream::set_ttl`].
592    ///
593    /// # Examples
594    ///
595    /// ```no_run
596    /// use std::net::TcpStream;
597    ///
598    /// let stream = TcpStream::connect("127.0.0.1:8080")
599    ///                        .expect("Couldn't connect to the server...");
600    /// stream.set_ttl(100).expect("set_ttl should succeed");
601    /// assert_eq!(stream.ttl().unwrap_or(0), 100);
602    /// ```
603    #[stable(feature = "net2_mutators", since = "1.9.0")]
604    pub fn ttl(&self) -> io::Result<u32> {
605        self.0.ttl()
606    }
607
608    /// Gets the value of the `SO_ERROR` option on this socket.
609    ///
610    /// This will retrieve the stored error in the underlying socket, clearing
611    /// the field in the process. This can be useful for checking errors between
612    /// calls.
613    ///
614    /// # Examples
615    ///
616    /// ```no_run
617    /// use std::net::TcpStream;
618    ///
619    /// let stream = TcpStream::connect("127.0.0.1:8080")
620    ///                        .expect("Couldn't connect to the server...");
621    /// stream.take_error().expect("No error was expected...");
622    /// ```
623    #[stable(feature = "net2_mutators", since = "1.9.0")]
624    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
625        self.0.take_error()
626    }
627
628    /// Moves this TCP stream into or out of nonblocking mode.
629    ///
630    /// This will result in `read`, `write`, `recv` and `send` system operations
631    /// becoming nonblocking, i.e., immediately returning from their calls.
632    /// If the IO operation is successful, `Ok` is returned and no further
633    /// action is required. If the IO operation could not be completed and needs
634    /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
635    /// returned.
636    ///
637    /// On most Unix platforms, calling this method corresponds to calling `ioctl`
638    /// `FIONBIO`. On Windows, calling this method corresponds to calling
639    /// `ioctlsocket` `FIONBIO`.
640    ///
641    /// # Examples
642    ///
643    /// Reading bytes from a TCP stream in non-blocking mode:
644    ///
645    /// ```no_run
646    /// use std::io::{self, Read};
647    /// use std::net::TcpStream;
648    ///
649    /// let mut stream = TcpStream::connect("127.0.0.1:7878")
650    ///     .expect("Couldn't connect to the server...");
651    /// stream.set_nonblocking(true).expect("set_nonblocking should succeed");
652    ///
653    /// # fn wait_for_fd() { unimplemented!() }
654    /// let mut buf = vec![];
655    /// loop {
656    ///     match stream.read_to_end(&mut buf) {
657    ///         Ok(_) => break,
658    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
659    ///             // wait until network socket is ready, typically implemented
660    ///             // via platform-specific APIs such as epoll or IOCP
661    ///             wait_for_fd();
662    ///         }
663    ///         Err(e) => panic!("encountered IO error: {e}"),
664    ///     };
665    /// };
666    /// println!("bytes: {buf:?}");
667    /// ```
668    #[stable(feature = "net2_mutators", since = "1.9.0")]
669    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
670        self.0.set_nonblocking(nonblocking)
671    }
672}
673
674// In addition to the `impl`s here, `TcpStream` also has `impl`s for
675// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
676// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
677// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
678// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
679
680#[stable(feature = "rust1", since = "1.0.0")]
681impl Read for TcpStream {
682    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
683        self.0.read(buf)
684    }
685
686    fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
687        self.0.read_buf(buf)
688    }
689
690    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
691        self.0.read_vectored(bufs)
692    }
693
694    #[inline]
695    fn is_read_vectored(&self) -> bool {
696        self.0.is_read_vectored()
697    }
698}
699#[stable(feature = "rust1", since = "1.0.0")]
700impl Write for TcpStream {
701    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
702        self.0.write(buf)
703    }
704
705    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
706        self.0.write_vectored(bufs)
707    }
708
709    #[inline]
710    fn is_write_vectored(&self) -> bool {
711        self.0.is_write_vectored()
712    }
713
714    #[inline]
715    fn flush(&mut self) -> io::Result<()> {
716        Ok(())
717    }
718}
719#[stable(feature = "rust1", since = "1.0.0")]
720impl Read for &TcpStream {
721    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
722        self.0.read(buf)
723    }
724
725    fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
726        self.0.read_buf(buf)
727    }
728
729    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
730        self.0.read_vectored(bufs)
731    }
732
733    #[inline]
734    fn is_read_vectored(&self) -> bool {
735        self.0.is_read_vectored()
736    }
737}
738#[stable(feature = "rust1", since = "1.0.0")]
739impl Write for &TcpStream {
740    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
741        self.0.write(buf)
742    }
743
744    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
745        self.0.write_vectored(bufs)
746    }
747
748    #[inline]
749    fn is_write_vectored(&self) -> bool {
750        self.0.is_write_vectored()
751    }
752
753    #[inline]
754    fn flush(&mut self) -> io::Result<()> {
755        Ok(())
756    }
757}
758
759impl AsInner<net_imp::TcpStream> for TcpStream {
760    #[inline]
761    fn as_inner(&self) -> &net_imp::TcpStream {
762        &self.0
763    }
764}
765
766impl FromInner<net_imp::TcpStream> for TcpStream {
767    fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
768        TcpStream(inner)
769    }
770}
771
772impl IntoInner<net_imp::TcpStream> for TcpStream {
773    fn into_inner(self) -> net_imp::TcpStream {
774        self.0
775    }
776}
777
778#[stable(feature = "rust1", since = "1.0.0")]
779impl fmt::Debug for TcpStream {
780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781        self.0.fmt(f)
782    }
783}
784
785impl TcpListener {
786    /// Creates a new `TcpListener` which will be bound to the specified
787    /// address.
788    ///
789    /// The returned listener is ready for accepting connections.
790    ///
791    /// Binding with a port number of 0 will request that the OS assigns a port
792    /// to this listener. The port allocated can be queried via the
793    /// [`TcpListener::local_addr`] method.
794    ///
795    /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
796    /// its documentation for concrete examples.
797    ///
798    /// If `addr` yields multiple addresses, `bind` will be attempted with
799    /// each of the addresses until one succeeds and returns the listener. If
800    /// none of the addresses succeed in creating a listener, the error returned
801    /// from the last attempt (the last address) is returned.
802    ///
803    /// # Examples
804    ///
805    /// Creates a TCP listener bound to `127.0.0.1:80`:
806    ///
807    /// ```no_run
808    /// use std::net::TcpListener;
809    ///
810    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
811    /// ```
812    ///
813    /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
814    /// TCP listener bound to `127.0.0.1:443`:
815    ///
816    /// ```no_run
817    /// use std::net::{SocketAddr, TcpListener};
818    ///
819    /// let addrs = [
820    ///     SocketAddr::from(([127, 0, 0, 1], 80)),
821    ///     SocketAddr::from(([127, 0, 0, 1], 443)),
822    /// ];
823    /// let listener = TcpListener::bind(&addrs[..]).unwrap();
824    /// ```
825    ///
826    /// Creates a TCP listener bound to a port assigned by the operating system
827    /// at `127.0.0.1`.
828    ///
829    /// ```no_run
830    /// use std::net::TcpListener;
831    ///
832    /// let socket = TcpListener::bind("127.0.0.1:0").unwrap();
833    /// ```
834    #[stable(feature = "rust1", since = "1.0.0")]
835    pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
836        net_imp::TcpListener::bind(addr).map(TcpListener)
837    }
838
839    /// Returns the local socket address of this listener.
840    ///
841    /// # Examples
842    ///
843    /// ```no_run
844    /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
845    ///
846    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
847    /// assert_eq!(listener.local_addr().unwrap(),
848    ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
849    /// ```
850    #[stable(feature = "rust1", since = "1.0.0")]
851    pub fn local_addr(&self) -> io::Result<SocketAddr> {
852        self.0.socket_addr()
853    }
854
855    /// Creates a new independently owned handle to the underlying socket.
856    ///
857    /// The returned [`TcpListener`] is a reference to the same socket that this
858    /// object references. Both handles can be used to accept incoming
859    /// connections and options set on one listener will affect the other.
860    ///
861    /// # Examples
862    ///
863    /// ```no_run
864    /// use std::net::TcpListener;
865    ///
866    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
867    /// let listener_clone = listener.try_clone().unwrap();
868    /// ```
869    #[stable(feature = "rust1", since = "1.0.0")]
870    pub fn try_clone(&self) -> io::Result<TcpListener> {
871        self.0.duplicate().map(TcpListener)
872    }
873
874    /// Accept a new incoming connection from this listener.
875    ///
876    /// This function will block the calling thread until a new TCP connection
877    /// is established. When established, the corresponding [`TcpStream`] and the
878    /// remote peer's address will be returned.
879    ///
880    /// # Errors
881    ///
882    /// Some errors this function returns do not indicate a problem with the
883    /// listener itself, and a program serving a long-lived listener will
884    /// usually want to handle them and keep accepting connections rather than
885    /// treat them as fatal. These include, but are not limited to:
886    ///
887    /// - An error specific to a single incoming connection that failed before
888    ///   it could be accepted, such as one aborted by the peer
889    ///   ([`ConnectionAborted`]). A later call may succeed immediately.
890    /// - An error from reaching the per-process or system-wide open file
891    ///   descriptor limit. The call can be retried once other file descriptors
892    ///   have been closed, typically after a short delay.
893    /// - An error from failing to allocate memory while accepting a connection
894    ///   ([`OutOfMemory`]).
895    ///
896    /// Which errors can occur is platform-specific. On Unix, [`Interrupted`]
897    /// errors are retried internally rather than being returned.
898    ///
899    /// [`ConnectionAborted`]: io::ErrorKind::ConnectionAborted
900    /// [`OutOfMemory`]: io::ErrorKind::OutOfMemory
901    /// [`Interrupted`]: io::ErrorKind::Interrupted
902    ///
903    /// # Examples
904    ///
905    /// ```no_run
906    /// use std::net::TcpListener;
907    ///
908    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
909    /// match listener.accept() {
910    ///     Ok((_socket, addr)) => println!("new client: {addr:?}"),
911    ///     Err(e) => println!("couldn't get client: {e:?}"),
912    /// }
913    /// ```
914    #[stable(feature = "rust1", since = "1.0.0")]
915    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
916        // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
917        // the `a` variable here is technically unused.
918        #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
919        self.0.accept().map(|(a, b)| (TcpStream(a), b))
920    }
921
922    /// Returns an iterator over the connections being received on this
923    /// listener.
924    ///
925    /// The returned iterator will never return [`None`] and will also not yield
926    /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
927    /// calling [`TcpListener::accept`] in a loop.
928    ///
929    /// # Errors
930    ///
931    /// Each connection yielded by the iterator can fail for the same reasons as
932    /// [`TcpListener::accept`]; see its documentation for details.
933    ///
934    /// # Examples
935    ///
936    /// ```no_run
937    /// use std::net::{TcpListener, TcpStream};
938    ///
939    /// fn handle_connection(stream: TcpStream) {
940    ///    //...
941    /// }
942    ///
943    /// fn main() -> std::io::Result<()> {
944    ///     let listener = TcpListener::bind("127.0.0.1:80")?;
945    ///
946    ///     for stream in listener.incoming() {
947    ///         match stream {
948    ///             Ok(stream) => {
949    ///                 handle_connection(stream);
950    ///             }
951    ///             Err(e) => { /* connection failed */ }
952    ///         }
953    ///     }
954    ///     Ok(())
955    /// }
956    /// ```
957    #[stable(feature = "rust1", since = "1.0.0")]
958    pub fn incoming(&self) -> Incoming<'_> {
959        Incoming { listener: self }
960    }
961
962    /// Turn this into an iterator over the connections being received on this
963    /// listener.
964    ///
965    /// The returned iterator will never return [`None`] and will also not yield
966    /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
967    /// calling [`TcpListener::accept`] in a loop.
968    ///
969    /// # Errors
970    ///
971    /// Each connection yielded by the iterator can fail for the same reasons as
972    /// [`TcpListener::accept`]; see its documentation for details.
973    ///
974    /// # Examples
975    ///
976    /// ```no_run
977    /// #![feature(tcplistener_into_incoming)]
978    /// use std::net::{TcpListener, TcpStream};
979    ///
980    /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
981    ///     let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
982    ///     listener.into_incoming()
983    ///         .filter_map(Result::ok) /* Ignore failed connections */
984    /// }
985    ///
986    /// fn main() -> std::io::Result<()> {
987    ///     for stream in listen_on(80) {
988    ///         /* handle the connection here */
989    ///     }
990    ///     Ok(())
991    /// }
992    /// ```
993    #[must_use = "`self` will be dropped if the result is not used"]
994    #[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
995    pub fn into_incoming(self) -> IntoIncoming {
996        IntoIncoming { listener: self }
997    }
998
999    /// Sets the value for the `IP_TTL` option on this socket.
1000    ///
1001    /// This value sets the time-to-live field that is used in every packet sent
1002    /// from this socket.
1003    ///
1004    /// # Examples
1005    ///
1006    /// ```no_run
1007    /// use std::net::TcpListener;
1008    ///
1009    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1010    /// listener.set_ttl(100).expect("set_ttl should succeed");
1011    /// ```
1012    #[stable(feature = "net2_mutators", since = "1.9.0")]
1013    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
1014        self.0.set_ttl(ttl)
1015    }
1016
1017    /// Gets the value of the `IP_TTL` option for this socket.
1018    ///
1019    /// For more information about this option, see [`TcpListener::set_ttl`].
1020    ///
1021    /// # Examples
1022    ///
1023    /// ```no_run
1024    /// use std::net::TcpListener;
1025    ///
1026    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1027    /// listener.set_ttl(100).expect("set_ttl should succeed");
1028    /// assert_eq!(listener.ttl().unwrap_or(0), 100);
1029    /// ```
1030    #[stable(feature = "net2_mutators", since = "1.9.0")]
1031    pub fn ttl(&self) -> io::Result<u32> {
1032        self.0.ttl()
1033    }
1034
1035    #[stable(feature = "net2_mutators", since = "1.9.0")]
1036    #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
1037    #[allow(missing_docs)]
1038    pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
1039        self.0.set_only_v6(only_v6)
1040    }
1041
1042    #[stable(feature = "net2_mutators", since = "1.9.0")]
1043    #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
1044    #[allow(missing_docs)]
1045    pub fn only_v6(&self) -> io::Result<bool> {
1046        self.0.only_v6()
1047    }
1048
1049    /// Gets the value of the `SO_ERROR` option on this socket.
1050    ///
1051    /// This will retrieve the stored error in the underlying socket, clearing
1052    /// the field in the process. This can be useful for checking errors between
1053    /// calls.
1054    ///
1055    /// # Examples
1056    ///
1057    /// ```no_run
1058    /// use std::net::TcpListener;
1059    ///
1060    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1061    /// listener.take_error().expect("No error was expected");
1062    /// ```
1063    #[stable(feature = "net2_mutators", since = "1.9.0")]
1064    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1065        self.0.take_error()
1066    }
1067
1068    /// Moves this TCP stream into or out of nonblocking mode.
1069    ///
1070    /// This will result in the `accept` operation becoming nonblocking,
1071    /// i.e., immediately returning from their calls. If the IO operation is
1072    /// successful, `Ok` is returned and no further action is required. If the
1073    /// IO operation could not be completed and needs to be retried, an error
1074    /// with kind [`io::ErrorKind::WouldBlock`] is returned.
1075    ///
1076    /// On most Unix platforms, calling this method corresponds to calling `ioctl`
1077    /// `FIONBIO`. On Windows, calling this method corresponds to calling
1078    /// `ioctlsocket` `FIONBIO`.
1079    ///
1080    /// # Examples
1081    ///
1082    /// Bind a TCP listener to an address, listen for connections, and read
1083    /// bytes in nonblocking mode:
1084    ///
1085    /// ```no_run
1086    /// use std::io;
1087    /// use std::net::TcpListener;
1088    ///
1089    /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
1090    /// listener.set_nonblocking(true).expect("set_nonblocking should succeed");
1091    ///
1092    /// # fn wait_for_fd() { unimplemented!() }
1093    /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
1094    /// for stream in listener.incoming() {
1095    ///     match stream {
1096    ///         Ok(s) => {
1097    ///             // do something with the TcpStream
1098    ///             handle_connection(s);
1099    ///         }
1100    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1101    ///             // wait until network socket is ready, typically implemented
1102    ///             // via platform-specific APIs such as epoll or IOCP
1103    ///             wait_for_fd();
1104    ///             continue;
1105    ///         }
1106    ///         Err(e) => panic!("encountered IO error: {e}"),
1107    ///     }
1108    /// }
1109    /// ```
1110    #[stable(feature = "net2_mutators", since = "1.9.0")]
1111    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1112        self.0.set_nonblocking(nonblocking)
1113    }
1114}
1115
1116// In addition to the `impl`s here, `TcpListener` also has `impl`s for
1117// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1118// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1119// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1120// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1121
1122#[stable(feature = "rust1", since = "1.0.0")]
1123impl<'a> Iterator for Incoming<'a> {
1124    type Item = io::Result<TcpStream>;
1125    fn next(&mut self) -> Option<io::Result<TcpStream>> {
1126        Some(self.listener.accept().map(|p| p.0))
1127    }
1128}
1129
1130#[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
1131impl FusedIterator for Incoming<'_> {}
1132
1133#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1134impl Iterator for IntoIncoming {
1135    type Item = io::Result<TcpStream>;
1136    fn next(&mut self) -> Option<io::Result<TcpStream>> {
1137        Some(self.listener.accept().map(|p| p.0))
1138    }
1139}
1140
1141#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1142impl FusedIterator for IntoIncoming {}
1143
1144impl AsInner<net_imp::TcpListener> for TcpListener {
1145    #[inline]
1146    fn as_inner(&self) -> &net_imp::TcpListener {
1147        &self.0
1148    }
1149}
1150
1151impl FromInner<net_imp::TcpListener> for TcpListener {
1152    fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1153        TcpListener(inner)
1154    }
1155}
1156
1157impl IntoInner<net_imp::TcpListener> for TcpListener {
1158    fn into_inner(self) -> net_imp::TcpListener {
1159        self.0
1160    }
1161}
1162
1163#[stable(feature = "rust1", since = "1.0.0")]
1164impl fmt::Debug for TcpListener {
1165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1166        self.0.fmt(f)
1167    }
1168}