Skip to content
This repository was archived by the owner on Aug 23, 2022. It is now read-only.

Commit

Permalink
add lookup_host and upgrade to v0.1.4
Browse files Browse the repository at this point in the history
  • Loading branch information
rainliu committed Jan 22, 2021
1 parent 20d73e0 commit 2dc1d4e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "webrtc-rs-util"
version = "0.1.3"
version = "0.1.4"
authors = ["Rain Liu <[email protected]>"]
edition = "2018"
description = "Utilities for WebRTC.rs stack"
Expand Down
22 changes: 22 additions & 0 deletions src/conn/conn_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use super::*;

#[tokio::test]
async fn test_conn_lookup_host() -> Result<()> {
let stun_serv_addr = "stun1.l.google.com:19302";

let ipv4_addr = lookup_host(true, stun_serv_addr).await?;
assert!(
ipv4_addr.is_ipv4(),
"expected ipv4 but got ipv6: {}",
ipv4_addr
);

let ipv6_addr = lookup_host(false, stun_serv_addr).await?;
assert!(
ipv6_addr.is_ipv6(),
"expected ipv6 but got ipv4: {}",
ipv6_addr
);

Ok(())
}
22 changes: 22 additions & 0 deletions src/conn/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ pub mod conn_udp;

#[cfg(test)]
mod conn_pipe_test;
#[cfg(test)]
mod conn_test;

use async_trait::async_trait;
use std::io::Result;
use std::net::SocketAddr;
use tokio::net::ToSocketAddrs;

#[async_trait]
pub trait Conn {
Expand All @@ -17,3 +20,22 @@ pub trait Conn {
async fn send_to(&self, buf: &[u8], target: SocketAddr) -> Result<usize>;
fn local_addr(&self) -> Result<SocketAddr>;
}

pub async fn lookup_host<T>(use_ipv4: bool, host: T) -> Result<SocketAddr>
where
T: ToSocketAddrs,
{
for remote_addr in tokio::net::lookup_host(host).await? {
if (use_ipv4 && remote_addr.is_ipv4()) || (!use_ipv4 && remote_addr.is_ipv6()) {
return Ok(remote_addr);
}
}

Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"No available {} IP address found!",
if use_ipv4 { "ipv4" } else { "ipv6" },
),
))
}

0 comments on commit 2dc1d4e

Please sign in to comment.