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