From 0c6b2d54bf97e3af648176796afc172fe22c298f Mon Sep 17 00:00:00 2001 From: ian Date: Mon, 20 May 2024 21:15:15 +0100 Subject: [PATCH] Fix mdns when listening with ipv6 wildcard (which includes ipv4) --- .../io/libp2p/discovery/MDnsDiscovery.kt | 6 +++++- .../io/libp2p/discovery/MDnsDiscoveryTest.kt | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/libp2p/src/main/kotlin/io/libp2p/discovery/MDnsDiscovery.kt b/libp2p/src/main/kotlin/io/libp2p/discovery/MDnsDiscovery.kt index 658103db3..e2afcaf61 100644 --- a/libp2p/src/main/kotlin/io/libp2p/discovery/MDnsDiscovery.kt +++ b/libp2p/src/main/kotlin/io/libp2p/discovery/MDnsDiscovery.kt @@ -76,7 +76,11 @@ class MDnsDiscovery( val address = host.listenAddresses().find { it.has(Protocol.IP4) } - val str = address?.getFirstComponent(Protocol.TCP)?.stringValue!! + val ipv6OnlyAddress = if (address == null) + host.listenAddresses().find { + it.has(Protocol.IP6) + } else address + val str = ipv6OnlyAddress?.getFirstComponent(Protocol.TCP)?.stringValue!! return Integer.parseInt(str) } diff --git a/libp2p/src/test/kotlin/io/libp2p/discovery/MDnsDiscoveryTest.kt b/libp2p/src/test/kotlin/io/libp2p/discovery/MDnsDiscoveryTest.kt index b0cfa93c6..f0acd5790 100644 --- a/libp2p/src/test/kotlin/io/libp2p/discovery/MDnsDiscoveryTest.kt +++ b/libp2p/src/test/kotlin/io/libp2p/discovery/MDnsDiscoveryTest.kt @@ -24,6 +24,18 @@ class MDnsDiscoveryTest { } } + val hostIpv6 = object : NullHost() { + override val peerId: PeerId = PeerId.fromPubKey( + generateEcdsaKeyPair().second + ) + + override fun listenAddresses(): List { + return listOf( + Multiaddr("/ip6/::/tcp/4001") + ) + } + } + val otherHost = object : NullHost() { override val peerId: PeerId = PeerId.fromPubKey( generateEcdsaKeyPair().second @@ -47,6 +59,15 @@ class MDnsDiscoveryTest { discoverer.stop().get(1, TimeUnit.SECONDS) } + @Test + fun `start and stop discovery ipv6`() { + val discoverer = MDnsDiscovery(hostIpv6, testServiceTag) + + discoverer.start().get(1, TimeUnit.SECONDS) + TimeUnit.MILLISECONDS.sleep(100) + discoverer.stop().get(1, TimeUnit.SECONDS) + } + @Test fun `start discovery and listen for self`() { var peerInfo: PeerInfo? = null