From 952160ec27be0257f51b00775b4f1866bc74ed3e Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Mon, 11 Sep 2023 12:15:02 +1000 Subject: [PATCH] Make example work in Firefox --- examples/browser-webrtc/README.md | 4 +--- examples/browser-webrtc/src/main.rs | 22 ++++++++++++++++------ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/examples/browser-webrtc/README.md b/examples/browser-webrtc/README.md index 1688307034a..d44cf879905 100644 --- a/examples/browser-webrtc/README.md +++ b/examples/browser-webrtc/README.md @@ -15,6 +15,4 @@ wasm-pack build --target web --out-dir static cargo run ``` -3. Open the following in a Chromium-based[^1] browser: http://localhost:8080 - -[^1]: Support in other browsers has not been verified. +3. Open the URL printed in the terminal diff --git a/examples/browser-webrtc/src/main.rs b/examples/browser-webrtc/src/main.rs index 6b22a58af1a..f919f047af5 100644 --- a/examples/browser-webrtc/src/main.rs +++ b/examples/browser-webrtc/src/main.rs @@ -17,10 +17,7 @@ use libp2p::{ }; use libp2p_webrtc as webrtc; use rand::thread_rng; -use std::{ - net::Ipv6Addr, - net::{IpAddr, Ipv4Addr, SocketAddr}, -}; +use std::net::{Ipv4Addr, SocketAddr}; use tower_http::cors::{Any, CorsLayer}; #[tokio::main] @@ -46,7 +43,7 @@ async fn main() -> anyhow::Result<()> { let mut swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build(); - let address_webrtc = Multiaddr::from(Ipv6Addr::UNSPECIFIED) + let address_webrtc = Multiaddr::from(Ipv4Addr::UNSPECIFIED) .with(Protocol::Udp(0)) .with(Protocol::WebRTCDirect); @@ -54,6 +51,14 @@ async fn main() -> anyhow::Result<()> { let address = loop { if let SwarmEvent::NewListenAddr { address, .. } = swarm.select_next_some().await { + if address + .iter() + .any(|e| e == Protocol::Ip4(Ipv4Addr::LOCALHOST)) + { + log::debug!("Ignoring localhost address to make sure the example works in Firefox"); + continue; + } + log::info!("Listening on: {address}"); break address; @@ -91,6 +96,11 @@ struct StaticFiles; /// Serve the Multiaddr we are listening on and the host files. pub(crate) async fn serve(libp2p_transport: Multiaddr) { + let listen_addr = match libp2p_transport.iter().next() { + Some(Protocol::Ip4(addr)) => addr, + _ => panic!("Expected 1st protocol to be IP4"), + }; + let server = Router::new() .route("/", get(get_index)) .route("/index.html", get(get_index)) @@ -103,7 +113,7 @@ pub(crate) async fn serve(libp2p_transport: Multiaddr) { .allow_methods([Method::GET]), ); - let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080); + let addr = SocketAddr::new(listen_addr.into(), 8080); log::info!("Serving client files at http://{addr}");