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