1 | //! Async networking primitives for TCP/UDP/Unix communication. |
2 | //! |
3 | //! This crate is an async version of [`std::net`] and [`std::os::unix::net`]. |
4 | //! |
5 | //! # Implementation |
6 | //! |
7 | //! This crate uses [`async-io`] for async I/O and [`blocking`] for DNS lookups. |
8 | //! |
9 | //! [`async-io`]: https://docs.rs/async-io |
10 | //! [`blocking`]: https://docs.rs/blocking |
11 | //! |
12 | //! # Examples |
13 | //! |
14 | //! A simple UDP server that echoes messages back to the sender: |
15 | //! |
16 | //! ```no_run |
17 | //! use async_net::UdpSocket; |
18 | //! |
19 | //! # futures_lite::future::block_on(async { |
20 | //! let socket = UdpSocket::bind("127.0.0.1:8080" ).await?; |
21 | //! let mut buf = vec![0u8; 1024]; |
22 | //! |
23 | //! loop { |
24 | //! let (n, addr) = socket.recv_from(&mut buf).await?; |
25 | //! socket.send_to(&buf[..n], &addr).await?; |
26 | //! } |
27 | //! # std::io::Result::Ok(()) }); |
28 | //! ``` |
29 | |
30 | #![forbid (unsafe_code)] |
31 | #![warn (missing_docs, missing_debug_implementations, rust_2018_idioms)] |
32 | #![doc ( |
33 | html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" |
34 | )] |
35 | #![doc ( |
36 | html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" |
37 | )] |
38 | |
39 | #[cfg (unix)] |
40 | pub mod unix; |
41 | |
42 | mod addr; |
43 | mod tcp; |
44 | mod udp; |
45 | |
46 | pub use addr::AsyncToSocketAddrs; |
47 | pub use tcp::{Incoming, TcpListener, TcpStream}; |
48 | pub use udp::UdpSocket; |
49 | |
50 | use std::io; |
51 | |
52 | #[doc (no_inline)] |
53 | pub use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6}; |
54 | |
55 | #[doc (no_inline)] |
56 | pub use std::net::AddrParseError; |
57 | |
58 | /// Converts or resolves addresses to [`SocketAddr`] values. |
59 | /// |
60 | /// # Examples |
61 | /// |
62 | /// ``` |
63 | /// # futures_lite::future::block_on(async { |
64 | /// for addr in async_net::resolve("google.com:80" ).await? { |
65 | /// println!("{}" , addr); |
66 | /// } |
67 | /// # std::io::Result::Ok(()) }); |
68 | /// ``` |
69 | pub async fn resolve<A: AsyncToSocketAddrs>(addr: A) -> io::Result<Vec<SocketAddr>> { |
70 | Ok(addr.to_socket_addrs().await?.collect()) |
71 | } |
72 | |