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    /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
609    ///
610    /// This value sets the unicast hop limit field that is used in every packet
611    /// sent from this socket.
612    ///
613    /// # Examples
614    ///
615    /// ```no_run
616    /// #![feature(ipv6_hop_limit)]
617    /// use std::net::TcpStream;
618    ///
619    /// let stream = TcpStream::connect("[::1]:12345")
620    ///     .expect("Couldn't connect to the server...");
621    /// stream.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
622    /// ```
623    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
624    pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
625        self.0.set_hop_limit_v6(limit)
626    }
627
628    /// Gets the value of the `IPV6_UNICAST_HOPS` option on this socket.
629    ///
630    /// For more information about this option, see [`TcpStream::set_hop_limit_v6`].
631    ///
632    /// # Examples
633    ///
634    /// ```no_run
635    /// #![feature(ipv6_hop_limit)]
636    /// use std::net::TcpStream;
637    ///
638    /// let stream = TcpStream::connect("[::1]:12345")
639    ///     .expect("Couldn't connect to the server...");
640    /// stream.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
641    /// assert_eq!(stream.hop_limit_v6().unwrap(), 88);
642    /// ```
643    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
644    pub fn hop_limit_v6(&self) -> io::Result<u8> {
645        self.0.hop_limit_v6()
646    }
647
648    /// Gets the value of the `SO_ERROR` option on this socket.
649    ///
650    /// This will retrieve the stored error in the underlying socket, clearing
651    /// the field in the process. This can be useful for checking errors between
652    /// calls.
653    ///
654    /// # Examples
655    ///
656    /// ```no_run
657    /// use std::net::TcpStream;
658    ///
659    /// let stream = TcpStream::connect("127.0.0.1:8080")
660    ///                        .expect("Couldn't connect to the server...");
661    /// stream.take_error().expect("No error was expected...");
662    /// ```
663    #[stable(feature = "net2_mutators", since = "1.9.0")]
664    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
665        self.0.take_error()
666    }
667
668    /// Moves this TCP stream into or out of nonblocking mode.
669    ///
670    /// This will result in `read`, `write`, `recv` and `send` system operations
671    /// becoming nonblocking, i.e., immediately returning from their calls.
672    /// If the IO operation is successful, `Ok` is returned and no further
673    /// action is required. If the IO operation could not be completed and needs
674    /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
675    /// returned.
676    ///
677    /// On most Unix platforms, calling this method corresponds to calling `ioctl`
678    /// `FIONBIO`. On Windows, calling this method corresponds to calling
679    /// `ioctlsocket` `FIONBIO`.
680    ///
681    /// # Examples
682    ///
683    /// Reading bytes from a TCP stream in non-blocking mode:
684    ///
685    /// ```no_run
686    /// use std::io::{self, Read};
687    /// use std::net::TcpStream;
688    ///
689    /// let mut stream = TcpStream::connect("127.0.0.1:7878")
690    ///     .expect("Couldn't connect to the server...");
691    /// stream.set_nonblocking(true).expect("set_nonblocking should succeed");
692    ///
693    /// # fn wait_for_fd() { unimplemented!() }
694    /// let mut buf = vec![];
695    /// loop {
696    ///     match stream.read_to_end(&mut buf) {
697    ///         Ok(_) => break,
698    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
699    ///             // wait until network socket is ready, typically implemented
700    ///             // via platform-specific APIs such as epoll or IOCP
701    ///             wait_for_fd();
702    ///         }
703    ///         Err(e) => panic!("encountered IO error: {e}"),
704    ///     };
705    /// };
706    /// println!("bytes: {buf:?}");
707    /// ```
708    #[stable(feature = "net2_mutators", since = "1.9.0")]
709    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
710        self.0.set_nonblocking(nonblocking)
711    }
712}
713
714// In addition to the `impl`s here, `TcpStream` also has `impl`s for
715// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
716// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
717// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
718// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
719
720#[stable(feature = "rust1", since = "1.0.0")]
721impl Read for TcpStream {
722    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
723        self.0.read(buf)
724    }
725
726    fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
727        self.0.read_buf(buf)
728    }
729
730    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
731        self.0.read_vectored(bufs)
732    }
733
734    #[inline]
735    fn is_read_vectored(&self) -> bool {
736        self.0.is_read_vectored()
737    }
738}
739#[stable(feature = "rust1", since = "1.0.0")]
740impl Write for TcpStream {
741    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
742        self.0.write(buf)
743    }
744
745    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
746        self.0.write_vectored(bufs)
747    }
748
749    #[inline]
750    fn is_write_vectored(&self) -> bool {
751        self.0.is_write_vectored()
752    }
753
754    #[inline]
755    fn flush(&mut self) -> io::Result<()> {
756        Ok(())
757    }
758}
759#[stable(feature = "rust1", since = "1.0.0")]
760impl Read for &TcpStream {
761    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
762        self.0.read(buf)
763    }
764
765    fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
766        self.0.read_buf(buf)
767    }
768
769    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
770        self.0.read_vectored(bufs)
771    }
772
773    #[inline]
774    fn is_read_vectored(&self) -> bool {
775        self.0.is_read_vectored()
776    }
777}
778#[stable(feature = "rust1", since = "1.0.0")]
779impl Write for &TcpStream {
780    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
781        self.0.write(buf)
782    }
783
784    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
785        self.0.write_vectored(bufs)
786    }
787
788    #[inline]
789    fn is_write_vectored(&self) -> bool {
790        self.0.is_write_vectored()
791    }
792
793    #[inline]
794    fn flush(&mut self) -> io::Result<()> {
795        Ok(())
796    }
797}
798
799impl AsInner<net_imp::TcpStream> for TcpStream {
800    #[inline]
801    fn as_inner(&self) -> &net_imp::TcpStream {
802        &self.0
803    }
804}
805
806impl FromInner<net_imp::TcpStream> for TcpStream {
807    fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
808        TcpStream(inner)
809    }
810}
811
812impl IntoInner<net_imp::TcpStream> for TcpStream {
813    fn into_inner(self) -> net_imp::TcpStream {
814        self.0
815    }
816}
817
818#[stable(feature = "rust1", since = "1.0.0")]
819impl fmt::Debug for TcpStream {
820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821        self.0.fmt(f)
822    }
823}
824
825impl TcpListener {
826    /// Creates a new `TcpListener` which will be bound to the specified
827    /// address.
828    ///
829    /// The returned listener is ready for accepting connections.
830    ///
831    /// Binding with a port number of 0 will request that the OS assigns a port
832    /// to this listener. The port allocated can be queried via the
833    /// [`TcpListener::local_addr`] method.
834    ///
835    /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
836    /// its documentation for concrete examples.
837    ///
838    /// If `addr` yields multiple addresses, `bind` will be attempted with
839    /// each of the addresses until one succeeds and returns the listener. If
840    /// none of the addresses succeed in creating a listener, the error returned
841    /// from the last attempt (the last address) is returned.
842    ///
843    /// # Examples
844    ///
845    /// Creates a TCP listener bound to `127.0.0.1:80`:
846    ///
847    /// ```no_run
848    /// use std::net::TcpListener;
849    ///
850    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
851    /// ```
852    ///
853    /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
854    /// TCP listener bound to `127.0.0.1:443`:
855    ///
856    /// ```no_run
857    /// use std::net::{SocketAddr, TcpListener};
858    ///
859    /// let addrs = [
860    ///     SocketAddr::from(([127, 0, 0, 1], 80)),
861    ///     SocketAddr::from(([127, 0, 0, 1], 443)),
862    /// ];
863    /// let listener = TcpListener::bind(&addrs[..]).unwrap();
864    /// ```
865    ///
866    /// Creates a TCP listener bound to a port assigned by the operating system
867    /// at `127.0.0.1`.
868    ///
869    /// ```no_run
870    /// use std::net::TcpListener;
871    ///
872    /// let socket = TcpListener::bind("127.0.0.1:0").unwrap();
873    /// ```
874    #[stable(feature = "rust1", since = "1.0.0")]
875    pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
876        net_imp::TcpListener::bind(addr).map(TcpListener)
877    }
878
879    /// Returns the local socket address of this listener.
880    ///
881    /// # Examples
882    ///
883    /// ```no_run
884    /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
885    ///
886    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
887    /// assert_eq!(listener.local_addr().unwrap(),
888    ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
889    /// ```
890    #[stable(feature = "rust1", since = "1.0.0")]
891    pub fn local_addr(&self) -> io::Result<SocketAddr> {
892        self.0.socket_addr()
893    }
894
895    /// Creates a new independently owned handle to the underlying socket.
896    ///
897    /// The returned [`TcpListener`] is a reference to the same socket that this
898    /// object references. Both handles can be used to accept incoming
899    /// connections and options set on one listener will affect the other.
900    ///
901    /// # Examples
902    ///
903    /// ```no_run
904    /// use std::net::TcpListener;
905    ///
906    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
907    /// let listener_clone = listener.try_clone().unwrap();
908    /// ```
909    #[stable(feature = "rust1", since = "1.0.0")]
910    pub fn try_clone(&self) -> io::Result<TcpListener> {
911        self.0.duplicate().map(TcpListener)
912    }
913
914    /// Accept a new incoming connection from this listener.
915    ///
916    /// This function will block the calling thread until a new TCP connection
917    /// is established. When established, the corresponding [`TcpStream`] and the
918    /// remote peer's address will be returned.
919    ///
920    /// # Errors
921    ///
922    /// Some errors this function returns do not indicate a problem with the
923    /// listener itself, and a program serving a long-lived listener will
924    /// usually want to handle them and keep accepting connections rather than
925    /// treat them as fatal. These include, but are not limited to:
926    ///
927    /// - An error specific to a single incoming connection that failed before
928    ///   it could be accepted, such as one aborted by the peer
929    ///   ([`ConnectionAborted`]). A later call may succeed immediately.
930    /// - An error from reaching the per-process or system-wide open file
931    ///   descriptor limit. The call can be retried once other file descriptors
932    ///   have been closed, typically after a short delay.
933    /// - An error from failing to allocate memory while accepting a connection
934    ///   ([`OutOfMemory`]).
935    ///
936    /// Which errors can occur is platform-specific. On Unix, [`Interrupted`]
937    /// errors are retried internally rather than being returned.
938    ///
939    /// [`ConnectionAborted`]: io::ErrorKind::ConnectionAborted
940    /// [`OutOfMemory`]: io::ErrorKind::OutOfMemory
941    /// [`Interrupted`]: io::ErrorKind::Interrupted
942    ///
943    /// # Examples
944    ///
945    /// ```no_run
946    /// use std::net::TcpListener;
947    ///
948    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
949    /// match listener.accept() {
950    ///     Ok((_socket, addr)) => println!("new client: {addr:?}"),
951    ///     Err(e) => println!("couldn't get client: {e:?}"),
952    /// }
953    /// ```
954    #[stable(feature = "rust1", since = "1.0.0")]
955    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
956        // On wasm*-unknown-unknown, `TcpStream` is uninhabited (as it's
957        // unsupported) and so the `a` variable here is technically unused.
958        #[cfg_attr(all(target_family = "wasm", target_os = "unknown"), allow(unused_variables))]
959        self.0.accept().map(|(a, b)| (TcpStream(a), b))
960    }
961
962    /// Returns 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    /// use std::net::{TcpListener, TcpStream};
978    ///
979    /// fn handle_connection(stream: TcpStream) {
980    ///    //...
981    /// }
982    ///
983    /// fn main() -> std::io::Result<()> {
984    ///     let listener = TcpListener::bind("127.0.0.1:80")?;
985    ///
986    ///     for stream in listener.incoming() {
987    ///         match stream {
988    ///             Ok(stream) => {
989    ///                 handle_connection(stream);
990    ///             }
991    ///             Err(e) => { /* connection failed */ }
992    ///         }
993    ///     }
994    ///     Ok(())
995    /// }
996    /// ```
997    #[stable(feature = "rust1", since = "1.0.0")]
998    pub fn incoming(&self) -> Incoming<'_> {
999        Incoming { listener: self }
1000    }
1001
1002    /// Turn this into an iterator over the connections being received on this
1003    /// listener.
1004    ///
1005    /// The returned iterator will never return [`None`] and will also not yield
1006    /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
1007    /// calling [`TcpListener::accept`] in a loop.
1008    ///
1009    /// # Errors
1010    ///
1011    /// Each connection yielded by the iterator can fail for the same reasons as
1012    /// [`TcpListener::accept`]; see its documentation for details.
1013    ///
1014    /// # Examples
1015    ///
1016    /// ```no_run
1017    /// #![feature(tcplistener_into_incoming)]
1018    /// use std::net::{TcpListener, TcpStream};
1019    ///
1020    /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
1021    ///     let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
1022    ///     listener.into_incoming()
1023    ///         .filter_map(Result::ok) /* Ignore failed connections */
1024    /// }
1025    ///
1026    /// fn main() -> std::io::Result<()> {
1027    ///     for stream in listen_on(80) {
1028    ///         /* handle the connection here */
1029    ///     }
1030    ///     Ok(())
1031    /// }
1032    /// ```
1033    #[must_use = "`self` will be dropped if the result is not used"]
1034    #[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1035    pub fn into_incoming(self) -> IntoIncoming {
1036        IntoIncoming { listener: self }
1037    }
1038
1039    /// Sets the value for the `IP_TTL` option on this socket.
1040    ///
1041    /// This value sets the time-to-live field that is used in every packet sent
1042    /// from this socket.
1043    ///
1044    /// # Examples
1045    ///
1046    /// ```no_run
1047    /// use std::net::TcpListener;
1048    ///
1049    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1050    /// listener.set_ttl(100).expect("set_ttl should succeed");
1051    /// ```
1052    #[stable(feature = "net2_mutators", since = "1.9.0")]
1053    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
1054        self.0.set_ttl(ttl)
1055    }
1056
1057    /// Gets the value of the `IP_TTL` option for this socket.
1058    ///
1059    /// For more information about this option, see [`TcpListener::set_ttl`].
1060    ///
1061    /// # Examples
1062    ///
1063    /// ```no_run
1064    /// use std::net::TcpListener;
1065    ///
1066    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1067    /// listener.set_ttl(100).expect("set_ttl should succeed");
1068    /// assert_eq!(listener.ttl().unwrap_or(0), 100);
1069    /// ```
1070    #[stable(feature = "net2_mutators", since = "1.9.0")]
1071    pub fn ttl(&self) -> io::Result<u32> {
1072        self.0.ttl()
1073    }
1074
1075    /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
1076    ///
1077    /// This value sets the unicast hop limit field that is used in every packet
1078    /// sent from this socket.
1079    ///
1080    /// # Examples
1081    ///
1082    /// ```no_run
1083    /// #![feature(ipv6_hop_limit)]
1084    /// use std::net::TcpListener;
1085    ///
1086    /// let listener = TcpListener::bind("[::1]:12345").unwrap();
1087    /// listener.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
1088    /// ```
1089    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
1090    pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
1091        self.0.set_hop_limit_v6(limit)
1092    }
1093
1094    /// Gets the value of the `IPV6_UNICAST_HOPS` option on this socket.
1095    ///
1096    /// For more information about this option, see [`TcpListener::set_hop_limit_v6`].
1097    ///
1098    /// # Examples
1099    ///
1100    /// ```no_run
1101    /// #![feature(ipv6_hop_limit)]
1102    /// use std::net::TcpListener;
1103    ///
1104    /// let listener = TcpListener::bind("[::1]:12345").unwrap();
1105    /// listener.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
1106    /// assert_eq!(listener.hop_limit_v6().unwrap(), 88);
1107    /// ```
1108    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
1109    pub fn hop_limit_v6(&self) -> io::Result<u8> {
1110        self.0.hop_limit_v6()
1111    }
1112
1113    #[stable(feature = "net2_mutators", since = "1.9.0")]
1114    #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
1115    #[allow(missing_docs)]
1116    pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
1117        self.0.set_only_v6(only_v6)
1118    }
1119
1120    #[stable(feature = "net2_mutators", since = "1.9.0")]
1121    #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
1122    #[allow(missing_docs)]
1123    pub fn only_v6(&self) -> io::Result<bool> {
1124        self.0.only_v6()
1125    }
1126
1127    /// Gets the value of the `SO_ERROR` option on this socket.
1128    ///
1129    /// This will retrieve the stored error in the underlying socket, clearing
1130    /// the field in the process. This can be useful for checking errors between
1131    /// calls.
1132    ///
1133    /// # Examples
1134    ///
1135    /// ```no_run
1136    /// use std::net::TcpListener;
1137    ///
1138    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1139    /// listener.take_error().expect("`take_error` should succeed");
1140    /// ```
1141    #[stable(feature = "net2_mutators", since = "1.9.0")]
1142    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1143        self.0.take_error()
1144    }
1145
1146    /// Moves this TCP stream into or out of nonblocking mode.
1147    ///
1148    /// This will result in the `accept` operation becoming nonblocking,
1149    /// i.e., immediately returning from their calls. If the IO operation is
1150    /// successful, `Ok` is returned and no further action is required. If the
1151    /// IO operation could not be completed and needs to be retried, an error
1152    /// with kind [`io::ErrorKind::WouldBlock`] is returned.
1153    ///
1154    /// On most Unix platforms, calling this method corresponds to calling `ioctl`
1155    /// `FIONBIO`. On Windows, calling this method corresponds to calling
1156    /// `ioctlsocket` `FIONBIO`.
1157    ///
1158    /// # Examples
1159    ///
1160    /// Bind a TCP listener to an address, listen for connections, and read
1161    /// bytes in nonblocking mode:
1162    ///
1163    /// ```no_run
1164    /// use std::io;
1165    /// use std::net::TcpListener;
1166    ///
1167    /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
1168    /// listener.set_nonblocking(true).expect("set_nonblocking should succeed");
1169    ///
1170    /// # fn wait_for_fd() { unimplemented!() }
1171    /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
1172    /// for stream in listener.incoming() {
1173    ///     match stream {
1174    ///         Ok(s) => {
1175    ///             // do something with the TcpStream
1176    ///             handle_connection(s);
1177    ///         }
1178    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1179    ///             // wait until network socket is ready, typically implemented
1180    ///             // via platform-specific APIs such as epoll or IOCP
1181    ///             wait_for_fd();
1182    ///             continue;
1183    ///         }
1184    ///         Err(e) => panic!("encountered IO error: {e}"),
1185    ///     }
1186    /// }
1187    /// ```
1188    #[stable(feature = "net2_mutators", since = "1.9.0")]
1189    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1190        self.0.set_nonblocking(nonblocking)
1191    }
1192}
1193
1194// In addition to the `impl`s here, `TcpListener` also has `impl`s for
1195// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1196// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1197// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1198// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1199
1200#[stable(feature = "rust1", since = "1.0.0")]
1201impl<'a> Iterator for Incoming<'a> {
1202    type Item = io::Result<TcpStream>;
1203    fn next(&mut self) -> Option<io::Result<TcpStream>> {
1204        Some(self.listener.accept().map(|p| p.0))
1205    }
1206}
1207
1208#[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
1209impl FusedIterator for Incoming<'_> {}
1210
1211#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1212impl Iterator for IntoIncoming {
1213    type Item = io::Result<TcpStream>;
1214    fn next(&mut self) -> Option<io::Result<TcpStream>> {
1215        Some(self.listener.accept().map(|p| p.0))
1216    }
1217}
1218
1219#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1220impl FusedIterator for IntoIncoming {}
1221
1222impl AsInner<net_imp::TcpListener> for TcpListener {
1223    #[inline]
1224    fn as_inner(&self) -> &net_imp::TcpListener {
1225        &self.0
1226    }
1227}
1228
1229impl FromInner<net_imp::TcpListener> for TcpListener {
1230    fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1231        TcpListener(inner)
1232    }
1233}
1234
1235impl IntoInner<net_imp::TcpListener> for TcpListener {
1236    fn into_inner(self) -> net_imp::TcpListener {
1237        self.0
1238    }
1239}
1240
1241#[stable(feature = "rust1", since = "1.0.0")]
1242impl fmt::Debug for TcpListener {
1243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1244        self.0.fmt(f)
1245    }
1246}