def connect_socket(self, host, port): try: addr_info = io.AddrInfo(host, family=self.family) except Exception: raise NSPRError(error_code=error.PR_ADDRESS_NOT_SUPPORTED_ERROR, error_message="Cannot resolve %s using family %s" % (host, io.addr_family_name(self.family))) for net_addr in addr_info: root_logger.debug("Connecting: %s", net_addr) net_addr.port = port self.family = net_addr.family try: self._create_socket() self.sock.connect(net_addr) return except Exception as e: root_logger.debug("Could not connect socket to %s, error: %s", net_addr, str(e)) root_logger.debug("Try to continue with next family...") continue raise NSPRError( error_code=error.PR_ADDRESS_NOT_SUPPORTED_ERROR, error_message="Could not connect to %s using any address" % host)
class NSSAddressFamilyFallback(object): def __init__(self, family): self.sock_family = family self.family = self._get_nss_family(self.sock_family) def _get_nss_family(self, sock_family): """ Translate a family from python socket module to nss family. """ try: return _af_dict[sock_family] except KeyError: raise ValueError('Uknown socket family %d\n', sock_family) def _create_socket(self): self.sock = io.Socket(family=self.family) def connect_socket(self, host, port): try: addr_info = io.AddrInfo(host, family=self.family) except Exception: raise NSPRError( error_code=error.PR_ADDRESS_NOT_SUPPORTED_ERROR, error_message="Cannot resolve %s using family %s" % (host, io.addr_family_name(self.family))) for net_addr in addr_info: root_logger.debug("Connecting: %s", net_addr) net_addr.port = port self.family = net_addr.family try: self._create_socket() self.sock.connect(net_addr) return except Exception, e: root_logger.debug("Could not connect socket to %s, error: %s", net_addr, str(e)) root_logger.debug("Try to continue with next family...") continue raise NSPRError( error_code=error.PR_ADDRESS_NOT_SUPPORTED_ERROR, error_message="Could not connect to %s using any address" % host)