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