diff --git a/sambacc/commands/ctdb.py b/sambacc/commands/ctdb.py index 578db96..0f297fe 100644 --- a/sambacc/commands/ctdb.py +++ b/sambacc/commands/ctdb.py @@ -261,12 +261,48 @@ def ctdb_migrate(ctx: Context) -> None: ctdb.archive_tdb(ctx.instance_config, ctx.cli.archive) -def _lookup_hostname(hostname): - # XXX this is a nasty little hack. - ips = socket.gethostbyname_ex(hostname)[2] - addr = [ip for ip in ips if ip != "127.0.0.1"][0] - _logger.info(f"Determined address for {hostname}: {addr}") - return addr +def _lookup_hostname(hostname: str) -> str: + try: + addrinfo = socket.getaddrinfo( + hostname, None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM + ) + ipv4_addresses = [] + ipv6_addresses = [] + + for entry in addrinfo: + family, _, _, _, sockaddr = entry + ip_address = sockaddr[0] + + if ip_address.startswith("127.") or ip_address == "::1": + continue + + if family == socket.AF_INET: + ipv4_addresses.append(ip_address) + elif family == socket.AF_INET6: + ipv6_addresses.append(ip_address) + + preferred_address = ipv4_addresses[0] if ipv4_addresses else ( + ipv6_addresses[0] if ipv6_addresses else None + ) + + if preferred_address: + _logger.info( + f"Determined address for {hostname}: {preferred_address}" + ) + return preferred_address + else: + raise ValueError( + f"No valid IP address found for hostname '{hostname}'." + ) + + except socket.gaierror as e: + _logger.error(f"Failed to resolve hostname '{hostname}': {e}") + raise + + except IndexError: + raise ValueError( + f"No valid IP address found for hostname '{hostname}'." + ) @commands.command(name="ctdb-set-node", arg_func=_ctdb_set_node_args)