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