From be34f4cd5f1db4dc36eb44d92d0fccfdfd9afd54 Mon Sep 17 00:00:00 2001 From: some-du6e <103129948+some-du6e@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:20:35 -0600 Subject: [PATCH] Connect to a server's IPv4 address first, as vanilla does Vanilla resolves a server with InetAddress.getByName, and Java's default (java.net.preferIPv6Addresses=false) puts IPv4 addresses first. Horizon tried addresses in the system resolver's order, which on macOS puts IPv6 first: a server whose IPv6 address resets the connection showed "Connection reset by peer (os error 54)" where vanilla joined. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/src/connection.rs | 39 ++++++++++++++++++++--- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs index 8f7ae28cc..e7d465288 100644 --- a/crates/horizon-protocol/src/connection.rs +++ b/crates/horizon-protocol/src/connection.rs @@ -6,7 +6,7 @@ use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame}; use std::{ io::{Read, Write}, - net::{Shutdown, TcpStream, ToSocketAddrs}, + net::{Shutdown, SocketAddr, TcpStream, ToSocketAddrs}, sync::{ Arc, Condvar, Mutex, atomic::{AtomicI64, Ordering}, @@ -180,6 +180,13 @@ pub struct ConnWriter { pub threshold: Option, counters: Arc, } +/// InetAddress.getByName with Java's default `java.net.preferIPv6Addresses=false`: IPv4 addresses +/// first, whatever order the system resolver gives (macOS puts IPv6 first). A server whose IPv6 +/// address doesn't answer the game still lets vanilla in over IPv4. +fn ipv4_first(mut addrs: Vec) -> Vec { + addrs.sort_by_key(SocketAddr::is_ipv6); + addrs +} /// Both halves before the split. pub struct Connection { pub reader: ConnReader, @@ -187,10 +194,12 @@ pub struct Connection { } impl Connection { pub fn connect(host: &str, port: u16, timeout: Duration) -> Result { - let addrs: Vec<_> = (host, port) - .to_socket_addrs() - .map_err(|e| Error::new(format!("Unknown host {host}: {e}")))? - .collect(); + let addrs = ipv4_first( + (host, port) + .to_socket_addrs() + .map_err(|e| Error::new(format!("Unknown host {host}: {e}")))? + .collect(), + ); let mut last = Error::new(format!("Unknown host {host}")); for addr in addrs { match TcpStream::connect_timeout(&addr, timeout) { @@ -315,6 +324,26 @@ mod tests { use super::*; use std::net::TcpListener; + #[test] + fn ipv4_addresses_come_first_in_resolver_order() { + let a = |s: &str| s.parse::().unwrap(); + let resolved = vec![ + a("[2001:db8::1]:25565"), + a("192.0.2.1:25565"), + a("[2001:db8::2]:25565"), + a("10.0.0.1:25565"), + ]; + assert_eq!( + ipv4_first(resolved), + [ + a("192.0.2.1:25565"), + a("10.0.0.1:25565"), + a("[2001:db8::1]:25565"), + a("[2001:db8::2]:25565"), + ] + ); + } + #[test] fn loopback_with_compression_and_encryption() { let listener = TcpListener::bind("127.0.0.1:0").unwrap();