diff --git a/transports/quic/src/transport.rs b/transports/quic/src/transport.rs index 9f025cd63fc..16ffbc5a163 100644 --- a/transports/quic/src/transport.rs +++ b/transports/quic/src/transport.rs @@ -926,17 +926,21 @@ mod tests { let keypair = libp2p_identity::Keypair::generate_ed25519(); let config = Config::new(&keypair); let mut transport = crate::tokio::Transport::new(config); + let port = { + let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + socket.local_addr().unwrap().port() + }; transport .listen_on( ListenerId::next(), - "/ip4/0.0.0.0/udp/4001/quic-v1".parse().unwrap(), + format!("/ip4/0.0.0.0/udp/{port}/quic-v1").parse().unwrap(), ) .unwrap(); transport .listen_on( ListenerId::next(), - "/ip6/::/udp/4001/quic-v1".parse().unwrap(), + format!("/ip6/::/udp/{port}/quic-v1").parse().unwrap(), ) .unwrap(); } diff --git a/transports/tcp/src/lib.rs b/transports/tcp/src/lib.rs index b1737cf7bed..5efdf16fff5 100644 --- a/transports/tcp/src/lib.rs +++ b/transports/tcp/src/lib.rs @@ -346,13 +346,12 @@ where } } - fn create_socket(&self, socket_addr: &SocketAddr) -> io::Result { - let domain = if socket_addr.is_ipv4() { - Domain::IPV4 - } else { - Domain::IPV6 - }; - let socket = Socket::new(domain, Type::STREAM, Some(socket2::Protocol::TCP))?; + fn create_socket(&self, socket_addr: SocketAddr) -> io::Result { + let socket = Socket::new( + Domain::for_address(socket_addr), + Type::STREAM, + Some(socket2::Protocol::TCP), + )?; if socket_addr.is_ipv6() { socket.set_only_v6(true)?; } @@ -375,7 +374,7 @@ where id: ListenerId, socket_addr: SocketAddr, ) -> io::Result> { - let socket = self.create_socket(&socket_addr)?; + let socket = self.create_socket(socket_addr)?; socket.bind(&socket_addr.into())?; socket.listen(self.config.backlog as _)?; socket.set_nonblocking(true)?; @@ -476,7 +475,7 @@ where log::debug!("dialing {}", socket_addr); let socket = self - .create_socket(&socket_addr) + .create_socket(socket_addr) .map_err(TransportError::Other)?; if let Some(addr) = self.port_reuse.local_dial_addr(&socket_addr.ip()) { @@ -1329,4 +1328,42 @@ mod tests { assert!(rt.block_on(cycle_listeners::())); } } + + #[test] + fn test_listens_ipv4_ipv6_separately() { + fn test() { + let port = { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + }; + let mut tcp = Transport::::default().boxed(); + let listener_id = ListenerId::next(); + tcp.listen_on( + listener_id, + format!("/ip4/0.0.0.0/tcp/{port}").parse().unwrap(), + ) + .unwrap(); + tcp.listen_on( + ListenerId::next(), + format!("/ip6/::/tcp/{port}").parse().unwrap(), + ) + .unwrap(); + } + #[cfg(feature = "async-io")] + { + async_std::task::block_on(async { + test::(); + }) + } + #[cfg(feature = "tokio")] + { + let rt = ::tokio::runtime::Builder::new_current_thread() + .enable_io() + .build() + .unwrap(); + rt.block_on(async { + test::(); + }); + } + } }