Skip to content

Commit

Permalink
Add code to resolve external ip
Browse files Browse the repository at this point in the history
  • Loading branch information
billylindeman committed Oct 19, 2022
1 parent c99c16c commit 4ee7153
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions switchboard-sfu/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ async fn main() -> anyhow::Result<()> {
}
pretty_env_logger::init();

let _extip = switchboard_sfu::extip::resolve_external_ip().await?;

let addr = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:7000".to_string());
Expand Down
53 changes: 53 additions & 0 deletions switchboard-sfu/src/extip.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use anyhow::{format_err, Result};
use log::*;
use std::sync::Arc;
use tokio::sync::mpsc;

use webrtc::ice::agent::agent_config::AgentConfig;
use webrtc::ice::agent::Agent;
use webrtc::ice::candidate::*;
use webrtc::ice::network_type::*;
use webrtc::ice::url::Url;

pub async fn resolve_external_ip() -> Result<String> {
let ice_agent = Arc::new(
Agent::new(AgentConfig {
urls: vec![Url::parse_url("stun:stun.l.google.com:19302")?],
network_types: vec![NetworkType::Udp4],
..Default::default()
})
.await?,
);

let (tx, mut rx) = mpsc::channel(16);

ice_agent
.on_candidate(Box::new(
move |c: Option<Arc<dyn Candidate + Send + Sync>>| {
let tx_clone = tx.clone();
Box::pin(async move {
if let Some(c) = c {
debug!(
"Gathered External Candidate: {:?} {:?}",
c.address(),
c.candidate_type()
);

if c.candidate_type() == CandidateType::ServerReflexive {
tx_clone.send(c.address()).await.unwrap();
}
}
})
},
))
.await;

ice_agent.gather_candidates().await?;

if let Some(extip) = rx.recv().await {
debug!("Resolved external ip {}", extip);
return Ok(extip);
}

Err(format_err!("could not resolve external ip"))
}
1 change: 1 addition & 0 deletions switchboard-sfu/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod extip;
pub mod sfu;
pub mod signal;

Expand Down

0 comments on commit 4ee7153

Please sign in to comment.