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 `TCP_NODELAY` option on this socket.
481    ///
482    /// If set, this option disables the Nagle algorithm. This means that
483    /// segments are always sent as soon as possible, even if there is only a
484    /// small amount of data. When not set, data is buffered until there is a
485    /// sufficient amount to send out, thereby avoiding the frequent sending of
486    /// small packets.
487    ///
488    /// # Examples
489    ///
490    /// ```no_run
491    /// use std::net::TcpStream;
492    ///
493    /// let stream = TcpStream::connect("127.0.0.1:8080")
494    ///                        .expect("Couldn't connect to the server...");
495    /// stream.set_nodelay(true).expect("set_nodelay call failed");
496    /// ```
497    #[stable(feature = "net2_mutators", since = "1.9.0")]
498    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
499        self.0.set_nodelay(nodelay)
500    }
501
502    /// Gets the value of the `TCP_NODELAY` option on this socket.
503    ///
504    /// For more information about this option, see [`TcpStream::set_nodelay`].
505    ///
506    /// # Examples
507    ///
508    /// ```no_run
509    /// use std::net::TcpStream;
510    ///
511    /// let stream = TcpStream::connect("127.0.0.1:8080")
512    ///                        .expect("Couldn't connect to the server...");
513    /// stream.set_nodelay(true).expect("set_nodelay call failed");
514    /// assert_eq!(stream.nodelay().unwrap_or(false), true);
515    /// ```
516    #[stable(feature = "net2_mutators", since = "1.9.0")]
517    pub fn nodelay(&self) -> io::Result<bool> {
518        self.0.nodelay()
519    }
520
521    /// Sets the value for the `IP_TTL` option on this socket.
522    ///
523    /// This value sets the time-to-live field that is used in every packet sent
524    /// from this socket.
525    ///
526    /// # Examples
527    ///
528    /// ```no_run
529    /// use std::net::TcpStream;
530    ///
531    /// let stream = TcpStream::connect("127.0.0.1:8080")
532    ///                        .expect("Couldn't connect to the server...");
533    /// stream.set_ttl(100).expect("set_ttl call failed");
534    /// ```
535    #[stable(feature = "net2_mutators", since = "1.9.0")]
536    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
537        self.0.set_ttl(ttl)
538    }
539
540    /// Gets the value of the `IP_TTL` option for this socket.
541    ///
542    /// For more information about this option, see [`TcpStream::set_ttl`].
543    ///
544    /// # Examples
545    ///
546    /// ```no_run
547    /// use std::net::TcpStream;
548    ///
549    /// let stream = TcpStream::connect("127.0.0.1:8080")
550    ///                        .expect("Couldn't connect to the server...");
551    /// stream.set_ttl(100).expect("set_ttl call failed");
552    /// assert_eq!(stream.ttl().unwrap_or(0), 100);
553    /// ```
554    #[stable(feature = "net2_mutators", since = "1.9.0")]
555    pub fn ttl(&self) -> io::Result<u32> {
556        self.0.ttl()
557    }
558
559    /// Gets the value of the `SO_ERROR` option on this socket.
560    ///
561    /// This will retrieve the stored error in the underlying socket, clearing
562    /// the field in the process. This can be useful for checking errors between
563    /// calls.
564    ///
565    /// # Examples
566    ///
567    /// ```no_run
568    /// use std::net::TcpStream;
569    ///
570    /// let stream = TcpStream::connect("127.0.0.1:8080")
571    ///                        .expect("Couldn't connect to the server...");
572    /// stream.take_error().expect("No error was expected...");
573    /// ```
574    #[stable(feature = "net2_mutators", since = "1.9.0")]
575    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
576        self.0.take_error()
577    }
578
579    /// Moves this TCP stream into or out of nonblocking mode.
580    ///
581    /// This will result in `read`, `write`, `recv` and `send` system operations
582    /// becoming nonblocking, i.e., immediately returning from their calls.
583    /// If the IO operation is successful, `Ok` is returned and no further
584    /// action is required. If the IO operation could not be completed and needs
585    /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
586    /// returned.
587    ///
588    /// On Unix platforms, calling this method corresponds to calling `fcntl`
589    /// `FIONBIO`. On Windows calling this method corresponds to calling
590    /// `ioctlsocket` `FIONBIO`.
591    ///
592    /// # Examples
593    ///
594    /// Reading bytes from a TCP stream in non-blocking mode:
595    ///
596    /// ```no_run
597    /// use std::io::{self, Read};
598    /// use std::net::TcpStream;
599    ///
600    /// let mut stream = TcpStream::connect("127.0.0.1:7878")
601    ///     .expect("Couldn't connect to the server...");
602    /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
603    ///
604    /// # fn wait_for_fd() { unimplemented!() }
605    /// let mut buf = vec![];
606    /// loop {
607    ///     match stream.read_to_end(&mut buf) {
608    ///         Ok(_) => break,
609    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
610    ///             // wait until network socket is ready, typically implemented
611    ///             // via platform-specific APIs such as epoll or IOCP
612    ///             wait_for_fd();
613    ///         }
614    ///         Err(e) => panic!("encountered IO error: {e}"),
615    ///     };
616    /// };
617    /// println!("bytes: {buf:?}");
618    /// ```
619    #[stable(feature = "net2_mutators", since = "1.9.0")]
620    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
621        self.0.set_nonblocking(nonblocking)
622    }
623}
624
625// In addition to the `impl`s here, `TcpStream` also has `impl`s for
626// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
627// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
628// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
629// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
630
631#[stable(feature = "rust1", since = "1.0.0")]
632impl Read for TcpStream {
633    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
634        self.0.read(buf)
635    }
636
637    fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
638        self.0.read_buf(buf)
639    }
640
641    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
642        self.0.read_vectored(bufs)
643    }
644
645    #[inline]
646    fn is_read_vectored(&self) -> bool {
647        self.0.is_read_vectored()
648    }
649}
650#[stable(feature = "rust1", since = "1.0.0")]
651impl Write for TcpStream {
652    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
653        self.0.write(buf)
654    }
655
656    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
657        self.0.write_vectored(bufs)
658    }
659
660    #[inline]
661    fn is_write_vectored(&self) -> bool {
662        self.0.is_write_vectored()
663    }
664
665    #[inline]
666    fn flush(&mut self) -> io::Result<()> {
667        Ok(())
668    }
669}
670#[stable(feature = "rust1", since = "1.0.0")]
671impl Read for &TcpStream {
672    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
673        self.0.read(buf)
674    }
675
676    fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> io::Result<()> {
677        self.0.read_buf(buf)
678    }
679
680    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
681        self.0.read_vectored(bufs)
682    }
683
684    #[inline]
685    fn is_read_vectored(&self) -> bool {
686        self.0.is_read_vectored()
687    }
688}
689#[stable(feature = "rust1", since = "1.0.0")]
690impl Write for &TcpStream {
691    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
692        self.0.write(buf)
693    }
694
695    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
696        self.0.write_vectored(bufs)
697    }
698
699    #[inline]
700    fn is_write_vectored(&self) -> bool {
701        self.0.is_write_vectored()
702    }
703
704    #[inline]
705    fn flush(&mut self) -> io::Result<()> {
706        Ok(())
707    }
708}
709
710impl AsInner<net_imp::TcpStream> for TcpStream {
711    #[inline]
712    fn as_inner(&self) -> &net_imp::TcpStream {
713        &self.0
714    }
715}
716
717impl FromInner<net_imp::TcpStream> for TcpStream {
718    fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
719        TcpStream(inner)
720    }
721}
722
723impl IntoInner<net_imp::TcpStream> for TcpStream {
724    fn into_inner(self) -> net_imp::TcpStream {
725        self.0
726    }
727}
728
729#[stable(feature = "rust1", since = "1.0.0")]
730impl fmt::Debug for TcpStream {
731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732        self.0.fmt(f)
733    }
734}
735
736impl TcpListener {
737    /// Creates a new `TcpListener` which will be bound to the specified
738    /// address.
739    ///
740    /// The returned listener is ready for accepting connections.
741    ///
742    /// Binding with a port number of 0 will request that the OS assigns a port
743    /// to this listener. The port allocated can be queried via the
744    /// [`TcpListener::local_addr`] method.
745    ///
746    /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
747    /// its documentation for concrete examples.
748    ///
749    /// If `addr` yields multiple addresses, `bind` will be attempted with
750    /// each of the addresses until one succeeds and returns the listener. If
751    /// none of the addresses succeed in creating a listener, the error returned
752    /// from the last attempt (the last address) is returned.
753    ///
754    /// # Examples
755    ///
756    /// Creates a TCP listener bound to `127.0.0.1:80`:
757    ///
758    /// ```no_run
759    /// use std::net::TcpListener;
760    ///
761    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
762    /// ```
763    ///
764    /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
765    /// TCP listener bound to `127.0.0.1:443`:
766    ///
767    /// ```no_run
768    /// use std::net::{SocketAddr, TcpListener};
769    ///
770    /// let addrs = [
771    ///     SocketAddr::from(([127, 0, 0, 1], 80)),
772    ///     SocketAddr::from(([127, 0, 0, 1], 443)),
773    /// ];
774    /// let listener = TcpListener::bind(&addrs[..]).unwrap();
775    /// ```
776    ///
777    /// Creates a TCP listener bound to a port assigned by the operating system
778    /// at `127.0.0.1`.
779    ///
780    /// ```no_run
781    /// use std::net::TcpListener;
782    ///
783    /// let socket = TcpListener::bind("127.0.0.1:0").unwrap();
784    /// ```
785    #[stable(feature = "rust1", since = "1.0.0")]
786    pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
787        net_imp::TcpListener::bind(addr).map(TcpListener)
788    }
789
790    /// Returns the local socket address of this listener.
791    ///
792    /// # Examples
793    ///
794    /// ```no_run
795    /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
796    ///
797    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
798    /// assert_eq!(listener.local_addr().unwrap(),
799    ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
800    /// ```
801    #[stable(feature = "rust1", since = "1.0.0")]
802    pub fn local_addr(&self) -> io::Result<SocketAddr> {
803        self.0.socket_addr()
804    }
805
806    /// Creates a new independently owned handle to the underlying socket.
807    ///
808    /// The returned [`TcpListener`] is a reference to the same socket that this
809    /// object references. Both handles can be used to accept incoming
810    /// connections and options set on one listener will affect the other.
811    ///
812    /// # Examples
813    ///
814    /// ```no_run
815    /// use std::net::TcpListener;
816    ///
817    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
818    /// let listener_clone = listener.try_clone().unwrap();
819    /// ```
820    #[stable(feature = "rust1", since = "1.0.0")]
821    pub fn try_clone(&self) -> io::Result<TcpListener> {
822        self.0.duplicate().map(TcpListener)
823    }
824
825    /// Accept a new incoming connection from this listener.
826    ///
827    /// This function will block the calling thread until a new TCP connection
828    /// is established. When established, the corresponding [`TcpStream`] and the
829    /// remote peer's address will be returned.
830    ///
831    /// # Examples
832    ///
833    /// ```no_run
834    /// use std::net::TcpListener;
835    ///
836    /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
837    /// match listener.accept() {
838    ///     Ok((_socket, addr)) => println!("new client: {addr:?}"),
839    ///     Err(e) => println!("couldn't get client: {e:?}"),
840    /// }
841    /// ```
842    #[stable(feature = "rust1", since = "1.0.0")]
843    pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
844        // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
845        // the `a` variable here is technically unused.
846        #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
847        self.0.accept().map(|(a, b)| (TcpStream(a), b))
848    }
849
850    /// Returns an iterator over the connections being received on this
851    /// listener.
852    ///
853    /// The returned iterator will never return [`None`] and will also not yield
854    /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
855    /// calling [`TcpListener::accept`] in a loop.
856    ///
857    /// # Examples
858    ///
859    /// ```no_run
860    /// use std::net::{TcpListener, TcpStream};
861    ///
862    /// fn handle_connection(stream: TcpStream) {
863    ///    //...
864    /// }
865    ///
866    /// fn main() -> std::io::Result<()> {
867    ///     let listener = TcpListener::bind("127.0.0.1:80")?;
868    ///
869    ///     for stream in listener.incoming() {
870    ///         match stream {
871    ///             Ok(stream) => {
872    ///                 handle_connection(stream);
873    ///             }
874    ///             Err(e) => { /* connection failed */ }
875    ///         }
876    ///     }
877    ///     Ok(())
878    /// }
879    /// ```
880    #[stable(feature = "rust1", since = "1.0.0")]
881    pub fn incoming(&self) -> Incoming<'_> {
882        Incoming { listener: self }
883    }
884
885    /// Turn this into an iterator over the connections being received on this
886    /// listener.
887    ///
888    /// The returned iterator will never return [`None`] and will also not yield
889    /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
890    /// calling [`TcpListener::accept`] in a loop.
891    ///
892    /// # Examples
893    ///
894    /// ```no_run
895    /// #![feature(tcplistener_into_incoming)]
896    /// use std::net::{TcpListener, TcpStream};
897    ///
898    /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
899    ///     let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
900    ///     listener.into_incoming()
901    ///         .filter_map(Result::ok) /* Ignore failed connections */
902    /// }
903    ///
904    /// fn main() -> std::io::Result<()> {
905    ///     for stream in listen_on(80) {
906    ///         /* handle the connection here */
907    ///     }
908    ///     Ok(())
909    /// }
910    /// ```
911    #[must_use = "`self` will be dropped if the result is not used"]
912    #[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
913    pub fn into_incoming(self) -> IntoIncoming {
914        IntoIncoming { listener: self }
915    }
916
917    /// Sets the value for the `IP_TTL` option on this socket.
918    ///
919    /// This value sets the time-to-live field that is used in every packet sent
920    /// from this socket.
921    ///
922    /// # Examples
923    ///
924    /// ```no_run
925    /// use std::net::TcpListener;
926    ///
927    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
928    /// listener.set_ttl(100).expect("could not set TTL");
929    /// ```
930    #[stable(feature = "net2_mutators", since = "1.9.0")]
931    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
932        self.0.set_ttl(ttl)
933    }
934
935    /// Gets the value of the `IP_TTL` option for this socket.
936    ///
937    /// For more information about this option, see [`TcpListener::set_ttl`].
938    ///
939    /// # Examples
940    ///
941    /// ```no_run
942    /// use std::net::TcpListener;
943    ///
944    /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
945    /// listener.set_ttl(100).expect("could not set TTL");
946    /// assert_eq!(listener.ttl().unwrap_or(0), 100);
947    /// ```
948    #[stable(feature = "net2_mutators", since = "1.9.0")]
949    pub fn ttl(&self) -> io::Result<u32> {
950        self.0.ttl()
951    }
952
953    #[stable(feature = "net2_mutators", since = "1.9.0")]
954    #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
955    #[allow(missing_docs)]
956    pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
957        self.0.set_only_v6(only_v6)
958    }
959
960    #[stable(feature = "net2_mutators", since = "1.9.0")]
961    #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
962    #[allow(missing_docs)]
963    pub fn only_v6(&self) -> io::Result<bool> {
964        self.0.only_v6()
965    }
966
967    /// Gets the value of the `SO_ERROR` option on this socket.
968    ///
969    /// This will retrieve the stored error in the underlying socket, clearing
970    /// the field in the process. This can be useful for checking errors between
971    /// calls.
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.take_error().expect("No error was expected");
980    /// ```
981    #[stable(feature = "net2_mutators", since = "1.9.0")]
982    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
983        self.0.take_error()
984    }
985
986    /// Moves this TCP stream into or out of nonblocking mode.
987    ///
988    /// This will result in the `accept` operation becoming nonblocking,
989    /// i.e., immediately returning from their calls. If the IO operation is
990    /// successful, `Ok` is returned and no further action is required. If the
991    /// IO operation could not be completed and needs to be retried, an error
992    /// with kind [`io::ErrorKind::WouldBlock`] is returned.
993    ///
994    /// On Unix platforms, calling this method corresponds to calling `fcntl`
995    /// `FIONBIO`. On Windows calling this method corresponds to calling
996    /// `ioctlsocket` `FIONBIO`.
997    ///
998    /// # Examples
999    ///
1000    /// Bind a TCP listener to an address, listen for connections, and read
1001    /// bytes in nonblocking mode:
1002    ///
1003    /// ```no_run
1004    /// use std::io;
1005    /// use std::net::TcpListener;
1006    ///
1007    /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
1008    /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
1009    ///
1010    /// # fn wait_for_fd() { unimplemented!() }
1011    /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
1012    /// for stream in listener.incoming() {
1013    ///     match stream {
1014    ///         Ok(s) => {
1015    ///             // do something with the TcpStream
1016    ///             handle_connection(s);
1017    ///         }
1018    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1019    ///             // wait until network socket is ready, typically implemented
1020    ///             // via platform-specific APIs such as epoll or IOCP
1021    ///             wait_for_fd();
1022    ///             continue;
1023    ///         }
1024    ///         Err(e) => panic!("encountered IO error: {e}"),
1025    ///     }
1026    /// }
1027    /// ```
1028    #[stable(feature = "net2_mutators", since = "1.9.0")]
1029    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1030        self.0.set_nonblocking(nonblocking)
1031    }
1032}
1033
1034// In addition to the `impl`s here, `TcpListener` also has `impl`s for
1035// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1036// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1037// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1038// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1039
1040#[stable(feature = "rust1", since = "1.0.0")]
1041impl<'a> Iterator for Incoming<'a> {
1042    type Item = io::Result<TcpStream>;
1043    fn next(&mut self) -> Option<io::Result<TcpStream>> {
1044        Some(self.listener.accept().map(|p| p.0))
1045    }
1046}
1047
1048#[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
1049impl FusedIterator for Incoming<'_> {}
1050
1051#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1052impl Iterator for IntoIncoming {
1053    type Item = io::Result<TcpStream>;
1054    fn next(&mut self) -> Option<io::Result<TcpStream>> {
1055        Some(self.listener.accept().map(|p| p.0))
1056    }
1057}
1058
1059#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1060impl FusedIterator for IntoIncoming {}
1061
1062impl AsInner<net_imp::TcpListener> for TcpListener {
1063    #[inline]
1064    fn as_inner(&self) -> &net_imp::TcpListener {
1065        &self.0
1066    }
1067}
1068
1069impl FromInner<net_imp::TcpListener> for TcpListener {
1070    fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1071        TcpListener(inner)
1072    }
1073}
1074
1075impl IntoInner<net_imp::TcpListener> for TcpListener {
1076    fn into_inner(self) -> net_imp::TcpListener {
1077        self.0
1078    }
1079}
1080
1081#[stable(feature = "rust1", since = "1.0.0")]
1082impl fmt::Debug for TcpListener {
1083    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1084        self.0.fmt(f)
1085    }
1086}