tokio/net/tcp/
listener.rs

1use crate::io::{Interest, PollEvented};
2use crate::net::tcp::TcpStream;
3use crate::util::check_socket_for_blocking;
4
5cfg_not_wasi! {
6    use crate::net::{to_socket_addrs, ToSocketAddrs};
7}
8
9use std::fmt;
10use std::io;
11use std::net::{self, SocketAddr};
12use std::task::{ready, Context, Poll};
13
14cfg_net! {
15    /// A TCP socket server, listening for connections.
16    ///
17    /// You can accept a new connection by using the [`accept`](`TcpListener::accept`)
18    /// method.
19    ///
20    /// A `TcpListener` can be turned into a `Stream` with [`TcpListenerStream`].
21    ///
22    /// The socket will be closed when the value is dropped.
23    ///
24    /// [`TcpListenerStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.TcpListenerStream.html
25    ///
26    /// # Errors
27    ///
28    /// Note that accepting a connection can lead to various errors and not all
29    /// of them are necessarily fatal ‒ for example having too many open file
30    /// descriptors or the other side closing the connection while it waits in
31    /// an accept queue. These would terminate the stream if not handled in any
32    /// way.
33    ///
34    /// # Examples
35    ///
36    /// Using `accept`:
37    /// ```no_run
38    /// use tokio::net::TcpListener;
39    ///
40    /// use std::io;
41    ///
42    /// async fn process_socket<T>(socket: T) {
43    ///     # drop(socket);
44    ///     // do work with socket here
45    /// }
46    ///
47    /// #[tokio::main]
48    /// async fn main() -> io::Result<()> {
49    ///     let listener = TcpListener::bind("127.0.0.1:8080").await?;
50    ///
51    ///     loop {
52    ///         let (socket, _) = listener.accept().await?;
53    ///         process_socket(socket).await;
54    ///     }
55    /// }
56    /// ```
57    pub struct TcpListener {
58        io: PollEvented<mio::net::TcpListener>,
59    }
60}
61
62impl TcpListener {
63    cfg_not_wasi! {
64        /// Creates a new `TcpListener`, which will be bound to the specified address.
65        ///
66        /// The returned listener is ready for accepting connections.
67        ///
68        /// Binding with a port number of 0 will request that the OS assigns a port
69        /// to this listener. The port allocated can be queried via the `local_addr`
70        /// method.
71        ///
72        /// The address type can be any implementor of the [`ToSocketAddrs`] trait.
73        /// If `addr` yields multiple addresses, bind will be attempted with each of
74        /// the addresses until one succeeds and returns the listener. If none of
75        /// the addresses succeed in creating a listener, the error returned from
76        /// the last attempt (the last address) is returned.
77        ///
78        /// This function sets the `SO_REUSEADDR` option on the socket on Unix.
79        ///
80        /// To configure the socket before binding, you can use the [`TcpSocket`]
81        /// type.
82        ///
83        /// [`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
84        /// [`TcpSocket`]: struct@crate::net::TcpSocket
85        ///
86        /// # Examples
87        ///
88        /// ```no_run
89        /// use tokio::net::TcpListener;
90        /// use std::io;
91        ///
92        /// #[tokio::main]
93        /// async fn main() -> io::Result<()> {
94        /// #   if cfg!(miri) { return Ok(()); } // No `socket` in miri.
95        ///     let listener = TcpListener::bind("127.0.0.1:2345").await?;
96        ///
97        ///     // use the listener
98        ///
99        ///     # let _ = listener;
100        ///     Ok(())
101        /// }
102        /// ```
103        pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
104            let addrs = to_socket_addrs(addr).await?;
105
106            let mut last_err = None;
107
108            for addr in addrs {
109                match TcpListener::bind_addr(addr) {
110                    Ok(listener) => return Ok(listener),
111                    Err(e) => last_err = Some(e),
112                }
113            }
114
115            Err(last_err.unwrap_or_else(|| {
116                io::Error::new(
117                    io::ErrorKind::InvalidInput,
118                    "could not resolve to any address",
119                )
120            }))
121        }
122
123        fn bind_addr(addr: SocketAddr) -> io::Result<TcpListener> {
124            let listener = mio::net::TcpListener::bind(addr)?;
125            TcpListener::new(listener)
126        }
127    }
128
129    /// Accepts a new incoming connection from this listener.
130    ///
131    /// This function will yield once a new TCP connection is established. When
132    /// established, the corresponding [`TcpStream`] and the remote peer's
133    /// address will be returned.
134    ///
135    /// # Cancel safety
136    ///
137    /// This method is cancel safe. If the method is used as the event in a
138    /// [`tokio::select!`](crate::select) statement and some other branch
139    /// completes first, then it is guaranteed that no new connections were
140    /// accepted by this method.
141    ///
142    /// [`TcpStream`]: struct@crate::net::TcpStream
143    ///
144    /// # Examples
145    ///
146    /// ```no_run
147    /// use tokio::net::TcpListener;
148    ///
149    /// use std::io;
150    ///
151    /// #[tokio::main]
152    /// async fn main() -> io::Result<()> {
153    ///     let listener = TcpListener::bind("127.0.0.1:8080").await?;
154    ///
155    ///     match listener.accept().await {
156    ///         Ok((_socket, addr)) => println!("new client: {:?}", addr),
157    ///         Err(e) => println!("couldn't get client: {:?}", e),
158    ///     }
159    ///
160    ///     Ok(())
161    /// }
162    /// ```
163    pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
164        let (mio, addr) = self
165            .io
166            .registration()
167            .async_io(Interest::READABLE, || self.io.accept())
168            .await?;
169
170        let stream = TcpStream::new(mio)?;
171        Ok((stream, addr))
172    }
173
174    /// Polls to accept a new incoming connection to this listener.
175    ///
176    /// If there is no connection to accept, `Poll::Pending` is returned and the
177    /// current task will be notified by a waker.  Note that on multiple calls
178    /// to `poll_accept`, only the `Waker` from the `Context` passed to the most
179    /// recent call is scheduled to receive a wakeup.
180    pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll<io::Result<(TcpStream, SocketAddr)>> {
181        loop {
182            let ev = ready!(self.io.registration().poll_read_ready(cx))?;
183
184            match self.io.accept() {
185                Ok((io, addr)) => {
186                    let io = TcpStream::new(io)?;
187                    return Poll::Ready(Ok((io, addr)));
188                }
189                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
190                    self.io.registration().clear_readiness(ev);
191                }
192                Err(e) => return Poll::Ready(Err(e)),
193            }
194        }
195    }
196
197    /// Creates new `TcpListener` from a `std::net::TcpListener`.
198    ///
199    /// This function is intended to be used to wrap a TCP listener from the
200    /// standard library in the Tokio equivalent.
201    ///
202    /// This API is typically paired with the `socket2` crate and the `Socket`
203    /// type to build up and customize a listener before it's shipped off to the
204    /// backing event loop. This allows configuration of options like
205    /// `SO_REUSEPORT`, binding to multiple addresses, etc.
206    ///
207    /// # Notes
208    ///
209    /// The caller is responsible for ensuring that the listener is in
210    /// non-blocking mode. Otherwise all I/O operations on the listener
211    /// will block the thread, which will cause unexpected behavior.
212    /// Non-blocking mode can be set using [`set_nonblocking`].
213    ///
214    /// Passing a listener in blocking mode is always erroneous,
215    /// and the behavior in that case may change in the future.
216    /// For example, it could panic.
217    ///
218    /// [`set_nonblocking`]: std::net::TcpListener::set_nonblocking
219    ///
220    /// # Examples
221    ///
222    /// ```rust,no_run
223    /// use std::error::Error;
224    /// use tokio::net::TcpListener;
225    ///
226    /// #[tokio::main]
227    /// async fn main() -> Result<(), Box<dyn Error>> {
228    ///     let std_listener = std::net::TcpListener::bind("127.0.0.1:0")?;
229    ///     std_listener.set_nonblocking(true)?;
230    ///     let listener = TcpListener::from_std(std_listener)?;
231    ///     Ok(())
232    /// }
233    /// ```
234    ///
235    /// # Panics
236    ///
237    /// This function panics if it is not called from within a runtime with
238    /// IO enabled.
239    ///
240    /// The runtime is usually set implicitly when this function is called
241    /// from a future driven by a tokio runtime, otherwise runtime can be set
242    /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
243    #[track_caller]
244    pub fn from_std(listener: net::TcpListener) -> io::Result<TcpListener> {
245        check_socket_for_blocking(&listener)?;
246
247        let io = mio::net::TcpListener::from_std(listener);
248        let io = PollEvented::new(io)?;
249        Ok(TcpListener { io })
250    }
251
252    /// Turns a [`tokio::net::TcpListener`] into a [`std::net::TcpListener`].
253    ///
254    /// The returned [`std::net::TcpListener`] will have nonblocking mode set as
255    /// `true`.  Use [`set_nonblocking`] to change the blocking mode if needed.
256    ///
257    /// # Examples
258    ///
259    /// ```rust,no_run
260    /// use std::error::Error;
261    ///
262    /// #[tokio::main]
263    /// async fn main() -> Result<(), Box<dyn Error>> {
264    ///     let tokio_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
265    ///     let std_listener = tokio_listener.into_std()?;
266    ///     std_listener.set_nonblocking(false)?;
267    ///     Ok(())
268    /// }
269    /// ```
270    ///
271    /// [`tokio::net::TcpListener`]: TcpListener
272    /// [`std::net::TcpListener`]: std::net::TcpListener
273    /// [`set_nonblocking`]: fn@std::net::TcpListener::set_nonblocking
274    pub fn into_std(self) -> io::Result<std::net::TcpListener> {
275        #[cfg(unix)]
276        {
277            use std::os::unix::io::{FromRawFd, IntoRawFd};
278            self.io
279                .into_inner()
280                .map(IntoRawFd::into_raw_fd)
281                .map(|raw_fd| unsafe { std::net::TcpListener::from_raw_fd(raw_fd) })
282        }
283
284        #[cfg(windows)]
285        {
286            use std::os::windows::io::{FromRawSocket, IntoRawSocket};
287            self.io
288                .into_inner()
289                .map(|io| io.into_raw_socket())
290                .map(|raw_socket| unsafe { std::net::TcpListener::from_raw_socket(raw_socket) })
291        }
292
293        #[cfg(target_os = "wasi")]
294        {
295            use std::os::wasi::io::{FromRawFd, IntoRawFd};
296            self.io
297                .into_inner()
298                .map(|io| io.into_raw_fd())
299                .map(|raw_fd| unsafe { std::net::TcpListener::from_raw_fd(raw_fd) })
300        }
301    }
302
303    cfg_not_wasi! {
304        pub(crate) fn new(listener: mio::net::TcpListener) -> io::Result<TcpListener> {
305            let io = PollEvented::new(listener)?;
306            Ok(TcpListener { io })
307        }
308    }
309
310    /// Returns the local address that this listener is bound to.
311    ///
312    /// This can be useful, for example, when binding to port 0 to figure out
313    /// which port was actually bound.
314    ///
315    /// # Examples
316    ///
317    /// ```rust,no_run
318    /// use tokio::net::TcpListener;
319    ///
320    /// use std::io;
321    /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
322    ///
323    /// #[tokio::main]
324    /// async fn main() -> io::Result<()> {
325    ///     let listener = TcpListener::bind("127.0.0.1:8080").await?;
326    ///
327    ///     assert_eq!(listener.local_addr()?,
328    ///                SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
329    ///
330    ///     Ok(())
331    /// }
332    /// ```
333    pub fn local_addr(&self) -> io::Result<SocketAddr> {
334        self.io.local_addr()
335    }
336
337    /// Gets the value of the `IP_TTL` option for this socket.
338    ///
339    /// For more information about this option, see [`set_ttl`].
340    ///
341    /// [`set_ttl`]: method@Self::set_ttl
342    ///
343    /// # Examples
344    ///
345    /// ```no_run
346    /// use tokio::net::TcpListener;
347    ///
348    /// use std::io;
349    ///
350    /// #[tokio::main]
351    /// async fn main() -> io::Result<()> {
352    ///    let listener = TcpListener::bind("127.0.0.1:0").await?;
353    ///
354    ///    listener.set_ttl(100).expect("could not set TTL");
355    ///    assert_eq!(listener.ttl()?, 100);
356    ///
357    ///    Ok(())
358    /// }
359    /// ```
360    pub fn ttl(&self) -> io::Result<u32> {
361        self.io.ttl()
362    }
363
364    /// Sets the value for the `IP_TTL` option on this socket.
365    ///
366    /// This value sets the time-to-live field that is used in every packet sent
367    /// from this socket.
368    ///
369    /// # Examples
370    ///
371    /// ```no_run
372    /// use tokio::net::TcpListener;
373    ///
374    /// use std::io;
375    ///
376    /// #[tokio::main]
377    /// async fn main() -> io::Result<()> {
378    ///     let listener = TcpListener::bind("127.0.0.1:0").await?;
379    ///
380    ///     listener.set_ttl(100).expect("could not set TTL");
381    ///
382    ///     Ok(())
383    /// }
384    /// ```
385    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
386        self.io.set_ttl(ttl)
387    }
388}
389
390impl TryFrom<net::TcpListener> for TcpListener {
391    type Error = io::Error;
392
393    /// Consumes stream, returning the tokio I/O object.
394    ///
395    /// This is equivalent to
396    /// [`TcpListener::from_std(stream)`](TcpListener::from_std).
397    fn try_from(stream: net::TcpListener) -> Result<Self, Self::Error> {
398        Self::from_std(stream)
399    }
400}
401
402impl fmt::Debug for TcpListener {
403    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404        (*self.io).fmt(f)
405    }
406}
407
408#[cfg(unix)]
409mod sys {
410    use super::TcpListener;
411    use std::os::unix::prelude::*;
412
413    impl AsRawFd for TcpListener {
414        fn as_raw_fd(&self) -> RawFd {
415            self.io.as_raw_fd()
416        }
417    }
418
419    impl AsFd for TcpListener {
420        fn as_fd(&self) -> BorrowedFd<'_> {
421            unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
422        }
423    }
424}
425
426cfg_unstable! {
427    #[cfg(target_os = "wasi")]
428    mod sys {
429        use super::TcpListener;
430        use std::os::wasi::prelude::*;
431
432        impl AsRawFd for TcpListener {
433            fn as_raw_fd(&self) -> RawFd {
434                self.io.as_raw_fd()
435            }
436        }
437
438        impl AsFd for TcpListener {
439            fn as_fd(&self) -> BorrowedFd<'_> {
440                unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
441            }
442        }
443    }
444}
445
446cfg_windows! {
447    use crate::os::windows::io::{AsRawSocket, RawSocket, AsSocket, BorrowedSocket};
448
449    impl AsRawSocket for TcpListener {
450        fn as_raw_socket(&self) -> RawSocket {
451            self.io.as_raw_socket()
452        }
453    }
454
455    impl AsSocket for TcpListener {
456        fn as_socket(&self) -> BorrowedSocket<'_> {
457            unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
458        }
459    }
460}