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