From 3ace1c6ac9d0d3de26c8709b4460bca2a09fe253 Mon Sep 17 00:00:00 2001 From: secretJod <144058972+secretJod@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:31:06 +0530 Subject: [PATCH] Skip empty bootstrap_servers entries in collect_hosts A trailing comma or blank entry (e.g. "b1:9092,b2:9092,") produced a ('', 9092) host, which getaddrinfo resolves to localhost. The java client trims entries and ignores empty ones; do the same. --- kafka/cluster.py | 6 +++++- test/test_cluster.py | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/kafka/cluster.py b/kafka/cluster.py index 4cf3cc6b7..d93ac367b 100644 --- a/kafka/cluster.py +++ b/kafka/cluster.py @@ -728,7 +728,11 @@ def collect_hosts(hosts, randomize=True): result = [] for host_port in hosts: # ignore leading SECURITY_PROTOCOL:// to mimic java client - host_port = re.sub('^.*://', '', host_port) + host_port = re.sub('^.*://', '', host_port.strip()) + # skip empty entries (e.g. a trailing comma), like the java client does; + # otherwise '' resolves to localhost:9092 + if not host_port: + continue host, port, afi = get_ip_port_afi(host_port) result.append((host, port, afi)) diff --git a/test/test_cluster.py b/test/test_cluster.py index e4a4b726d..9f6e9506c 100644 --- a/test/test_cluster.py +++ b/test/test_cluster.py @@ -414,6 +414,19 @@ def test_collect_hosts__protocol(self): ('fizz.buzz', 5678, socket.AF_UNSPEC), ]) + @pytest.mark.parametrize('hosts', [ + "localhost:1234,", + "localhost:1234,,localhost", + " localhost:1234 , ", + "localhost:1234,PLAINTEXT://", + ['localhost:1234', ' ', ''], + ]) + def test_collect_hosts__ignores_empty_entries(self, hosts): + # An empty entry would otherwise become ('', 9092), which resolves to localhost + results = collect_hosts(hosts) + assert results + assert all(host == 'localhost' for host, _port, _afi in results) + class TestExpandToCanonicalBootstrapHosts: def test_expands_multi_ip_host_to_canonical_names(self):