1use std::io;
2use std::net::{Ipv4Addr, SocketAddrV4};
3
4use async_trait::async_trait;
5use tokio::net::UdpSocket;
6
7use crate::asynchronous::{new_natpmp_async_with, AsyncUdpSocket, NatpmpAsync};
8use crate::{get_default_gateway, Error, Result, NATPMP_PORT};
9
10#[async_trait]
11impl AsyncUdpSocket for UdpSocket {
12 async fn connect(&self, addr: &str) -> io::Result<()> {
13 self.connect(addr).await
14 }
15
16 async fn send(&self, buf: &[u8]) -> io::Result<usize> {
17 self.send(buf).await
18 }
19
20 async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
21 self.recv(buf).await
22 }
23}
24
25pub async fn new_tokio_natpmp() -> Result<NatpmpAsync<UdpSocket>> {
38 let gateway = get_default_gateway()?;
39 new_tokio_natpmp_with(gateway).await
40}
41
42pub async fn new_tokio_natpmp_with(gateway: Ipv4Addr) -> Result<NatpmpAsync<UdpSocket>> {
56 let s = UdpSocket::bind("0.0.0.0:0")
57 .await
58 .map_err(|_| Error::NATPMP_ERR_SOCKETERROR)?;
59 let gateway_sockaddr = SocketAddrV4::new(gateway, NATPMP_PORT);
60 if s.connect(gateway_sockaddr).await.is_err() {
61 return Err(Error::NATPMP_ERR_CONNECTERR);
62 }
63 let n = new_natpmp_async_with(s, gateway);
64 Ok(n)
65}