From 3659102ce26774d137029d4d00af2de70b1193e5 Mon Sep 17 00:00:00 2001 From: Benjamin Gentil Date: Fri, 8 Apr 2022 16:05:28 +0200 Subject: [PATCH] fix ipv4/ipv6 fallback The current fallback to ipv6 won't work in most cases (successful socket.socket(socket.AF_INET) doesn't means ipv4 connectivity on the remote host). What we are trying to do, is to connect to the right IP (v4/v6) depending on DNS records (A / AAAA) and system preference and it's already done system-wide via getaddrinfo. --- pyzabbix/sender.py | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/pyzabbix/sender.py b/pyzabbix/sender.py index 250c3ab..be139cc 100644 --- a/pyzabbix/sender.py +++ b/pyzabbix/sender.py @@ -385,21 +385,29 @@ def _chunk_send(self, metrics): packet = self._create_packet(request) for host_addr in self.zabbix_uri: - logger.debug('Sending data to %s', host_addr) - - try: - # IPv4 - connection_ = socket.socket(socket.AF_INET) - except socket.error: - # IPv6 + logger.debug("Sending data to %s", host_addr) + + host, port = host_addr + conn_ = None + for res in socket.getaddrinfo( + host, port, socket.AF_UNSPEC, socket.SOCK_STREAM + ): + af, socktype, proto, canonname, sa = res try: - connection_ = socket.socket(socket.AF_INET6) - except socket.error: - raise Exception("Error creating socket for {host_addr}".format(host_addr=host_addr)) + conn_ = socket.socket(af, socktype, proto) + except OSError as msg: + conn_ = None + continue + break + + if conn_ is None: + raise Exception( + "Error creating socket for {host_addr}".format(host_addr=host_addr) + ) if self.socket_wrapper: - connection = self.socket_wrapper(connection_) + connection = self.socket_wrapper(conn_) else: - connection = connection_ + connection = conn_ connection.settimeout(self.timeout)