natpmp/
a_tokio.rs

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
25/// Create a tokio NAT-PMP object with default gateway
26///
27/// # Errors
28/// * [`Error::NATPMP_ERR_SOCKETERROR`](enum.Error.html#variant.NATPMP_ERR_SOCKETERROR)
29/// * [`Error::NATPMP_ERR_CONNECTERR`](enum.Error.html#variant.NATPMP_ERR_CONNECTERR)
30///
31/// # Examples
32/// ```
33/// use natpmp::*;
34///
35/// let n = new_tokio_natpmp().await?;
36/// ```
37pub async fn new_tokio_natpmp() -> Result<NatpmpAsync<UdpSocket>> {
38    let gateway = get_default_gateway()?;
39    new_tokio_natpmp_with(gateway).await
40}
41
42/// Create a tokio NAT-PMP object with specified gateway.
43///
44/// # Errors
45/// * [`Error::NATPMP_ERR_SOCKETERROR`](enum.Error.html#variant.NATPMP_ERR_SOCKETERROR)
46/// * [`Error::NATPMP_ERR_CONNECTERR`](enum.Error.html#variant.NATPMP_ERR_CONNECTERR)
47///
48/// # Examples
49/// ```
50/// use natpmp::*;
51///
52/// let gateway = get_default_gateway().unwrap();
53/// let n = new_tokio_natpmp_with(gateway).await?;
54/// ```
55pub 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}