当前位置: 首页>>代码示例>>Python>>正文


Python socket.getaddrinfo函数代码示例

本文整理汇总了Python中socket.getaddrinfo函数的典型用法代码示例。如果您正苦于以下问题:Python getaddrinfo函数的具体用法?Python getaddrinfo怎么用?Python getaddrinfo使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了getaddrinfo函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: is_hostname_sane

def is_hostname_sane(hostname):
    """Make sure the given host name is sane.

    Do enough to avoid shellcode from the environment.  There's
    no need to do more.

    :param str hostname: Host name to validate

    :returns: True if hostname is valid, otherwise false.
    :rtype: bool

    """
    # hostnames & IPv4
    allowed = string.ascii_letters + string.digits + "-."
    if all([c in allowed for c in hostname]):
        return True

    if not ALLOW_RAW_IPV6_SERVER:
        return False

    # ipv6 is messy and complicated, can contain %zoneindex etc.
    try:
        # is this a valid IPv6 address?
        socket.getaddrinfo(hostname, 443, socket.AF_INET6)
        return True
    except:
        return False
开发者ID:hpitas,项目名称:lets-encrypt-preview,代码行数:27,代码来源:client.py

示例2: _resolve_addrs

def _resolve_addrs(straddrs, port, ignore_unavailable=False, protocols=[socket.AF_INET, socket.AF_INET6]):
    """ Returns a tupel of tupels of (family, to, original_addr_family, original_addr).

    If ignore_unavailable is set, addresses for unavailable protocols are ignored.
    protocols determines the protocol family indices supported by the socket in use. """

    res = []
    for sa in straddrs:
        try:
            ais = socket.getaddrinfo(sa, port)
            for ai in ais:
                if ai[0] in protocols:
                    res.append((ai[0], ai[4], ai[0], ai[4][0]))
                    break
            else:
                # Try to convert from IPv4 to IPv6
                ai = ais[0]
                if ai[0] == socket.AF_INET and socket.AF_INET6 in protocols:
                    to = socket.getaddrinfo('::ffff:' + ai[4][0], port, socket.AF_INET6)[0][4]
                    res.append((socket.AF_INET6, to, ai[0], ai[4][0]))
        except socket.gaierror:
            if not ignore_unavailable:
                raise

    return res
开发者ID:phihag,项目名称:minusconf,代码行数:25,代码来源:minusconf.py

示例3: _getSession

    def _getSession(self, content):
        traphost = content['action_destination']
        port = content.get('port', 162)
        destination = '%s:%s' % (traphost, port)

        if not traphost or port <= 0:
            log.error("%s: SNMP trap host information %s is incorrect ", destination)
            return None

        community = content.get('community', 'public')
        version = content.get('version', 'v2c')

        session = self._sessions.get(destination, None)
        if session is None:
            log.debug("Creating SNMP trap session to %s", destination)

            # Test that the hostname and port are sane.
            try:
                getaddrinfo(traphost, port)
            except Exception:
                raise ActionExecutionException("The destination %s is not resolvable." % destination)

            session = netsnmp.Session((
                '-%s' % version,
                '-c', community,
                destination)
            )
            session.open()
            self._sessions[destination] = session

        return session
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:31,代码来源:actions.py

示例4: test_retry_limited

 def test_retry_limited(self):
   inet4_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
                    for _ in range(wsgi_server._PORT_0_RETRIES)]
   inet6_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
                    for _ in range(wsgi_server._PORT_0_RETRIES)]
   self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
   self.mox.StubOutWithMock(socket, 'getaddrinfo')
   socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                      socket.AI_PASSIVE).AndReturn(
                          [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                           (None, None, None, None, ('::1', 0, 'baz'))])
   for offset, (inet4_server, inet6_server) in enumerate(zip(
       inet4_servers, inet6_servers)):
     wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
         inet4_server)
     inet4_server.start()
     inet4_server.port = offset + 1
     wsgi_server._SingleAddressWsgiServer(('::1', offset + 1), None).AndReturn(
         inet6_server)
     inet6_server.start().AndRaise(
         wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use')))
     inet4_server.quit()
   self.mox.ReplayAll()
   self.assertRaises(wsgi_server.BindError, self.server.start)
   self.mox.VerifyAll()
开发者ID:zenlambda,项目名称:appengine-python3,代码行数:25,代码来源:wsgi_server_test.py

示例5: _create_remote_socket

    def _create_remote_socket(self, ip, port):
        if self._remote_udp:
            addrs_v6 = socket.getaddrinfo("::", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
            addrs = socket.getaddrinfo("0.0.0.0", 0, 0, socket.SOCK_DGRAM, socket.SOL_UDP)
        else:
            addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP)
        if len(addrs) == 0:
            raise Exception("getaddrinfo failed for %s:%d" % (ip, port))
        af, socktype, proto, canonname, sa = addrs[0]
        if self._forbidden_iplist:
            if common.to_str(sa[0]) in self._forbidden_iplist:
                raise Exception('IP %s is in forbidden list, reject' %
                                common.to_str(sa[0]))
        remote_sock = socket.socket(af, socktype, proto)
        self._remote_sock = remote_sock
        self._fd_to_handlers[remote_sock.fileno()] = self

        if self._remote_udp:
            af, socktype, proto, canonname, sa = addrs_v6[0]
            remote_sock_v6 = socket.socket(af, socktype, proto)
            self._remote_sock_v6 = remote_sock_v6
            self._fd_to_handlers[remote_sock_v6.fileno()] = self
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 32)
            remote_sock_v6.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024 * 32)

        remote_sock.setblocking(False)
        if self._remote_udp:
            pass
        else:
            remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        return remote_sock
开发者ID:konggil,项目名称:shadowsocks,代码行数:33,代码来源:tcprelay.py

示例6: resolve

def resolve(hostname, family=None):
    '''
    Resolves the hostname to one or more IP addresses through the operating
    system. Resolution is carried out for the given address family. If no
    address family is specified, only IPv4 and IPv6 addresses are returned. If
    multiple IP addresses are found, all are returned.

    :return: tuple of unique IP addresses
    '''
    af_ok = (AF_INET, AF_INET6)
    if family is not None and family not in af_ok:
        raise ValueError("Invalid AF_ '%s'" % family)
    ips = ()
    try:
        if family is None:
            addrinfo = socket.getaddrinfo(hostname, None)
        else:
            addrinfo = socket.getaddrinfo(hostname, None, family)
    except socket.gaierror as exc:
        log.debug("socket.getaddrinfo() raised an exception", exc_info=exc)
    else:
        if family is None:
            ips = tuple(set(
                        [item[4][0] for item in addrinfo if item[0] in af_ok]
                        ))
        else:
            ips = tuple(set([item[4][0] for item in addrinfo]))
    return ips
开发者ID:ChrisNolan1992,项目名称:python-dyndnsc,代码行数:28,代码来源:dns.py

示例7: address_info

    def address_info(self):
        if not self._address_info or (datetime.now() - self._address_info_resolved_time).seconds > ADDRESS_INFO_REFRESH_TIME:
            # converts addresses tuple to list and adds a 6th parameter for availability (None = not checked, True = available, False=not available) and a 7th parameter for the checking time
            addresses = None
            try:
                if self.ipc:
                    addresses = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, None, self.host, None)]
                else:
                    addresses = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG | socket.AI_V4MAPPED)
            except (socket.gaierror, AttributeError):
                pass

            if not addresses:  # if addresses not found or raised an exception (for example for bad flags) tries again without flags
                try:
                    addresses = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP)
                except socket.gaierror:
                    pass

            if addresses:
                self._address_info = [list(address) + [None, None] for address in addresses]
                self._address_info_resolved_time = datetime.now()
            else:
                self._address_info = []
                self._address_info_resolved_time = datetime(MINYEAR, 1, 1)  # smallest date

            if log_enabled(BASIC):
                for address in self._address_info:
                    log(BASIC, 'address for <%s> resolved as <%r>', self, address[:-2])
        return self._address_info
开发者ID:cfelder,项目名称:ldap3,代码行数:29,代码来源:server.py

示例8: get_hostname

def get_hostname(local = ''):
    if platform.system() in ['Windows', 'Microsoft']:
        if local == 'true':
            return '0.0.0.0'
        else:
            #have to change to IP address of machine to load data into if running over the network
            return '0.0.0.0'
    else:
        if local == 'true':
            #have to change to IP address of local machine if running over the network
            hostname = socket.gethostname()
            address_list = socket.getaddrinfo(hostname,None)
            if len(address_list) > 0:
                ipv6_tuple_index = len(address_list) - 1
                return address_list[ipv6_tuple_index][4][0]
            else:
                return hostname
        else:
            #have to change to IP address of machine to load data into if running over the network
            hostname = socket.gethostname()
            # getaddrinfo(host,port) returns a list of tuples
            # in the form of (family, socktype, proto, canonname, sockaddr)
            # and we extract the IP address from 'sockaddr'
            address_list = socket.getaddrinfo(hostname,None)
            if len(address_list) > 0:
                ipv6_tuple_index = len(address_list) - 1
                return address_list[ipv6_tuple_index][4][0]
            else:
                return hostname
开发者ID:adam8157,项目名称:gpdb,代码行数:29,代码来源:TEST.py

示例9: network_details

    def network_details():
        """
        Returns details about the network links
        """
        # Get IPv4 details
        ipv4_addresses = [info[4][0] for info in socket.getaddrinfo(
            socket.gethostname(), None, socket.AF_INET)]

        # Add localhost
        ipv4_addresses.extend(info[4][0] for info in socket.getaddrinfo(
            "localhost", None, socket.AF_INET))

        # Filter addresses
        ipv4_addresses = sorted(set(ipv4_addresses))

        try:
            # Get IPv6 details
            ipv6_addresses = [info[4][0] for info in socket.getaddrinfo(
                socket.gethostname(), None, socket.AF_INET6)]

            # Add localhost
            ipv6_addresses.extend(info[4][0] for info in socket.getaddrinfo(
                "localhost", None, socket.AF_INET6))

            # Filter addresses
            ipv6_addresses = sorted(set(ipv6_addresses))
        except (socket.gaierror, AttributeError):
            # AttributeError: AF_INET6 is missing in some versions of Python
            ipv6_addresses = None

        return {"IPv4": ipv4_addresses, "IPv6": ipv6_addresses,
                "host.name": socket.gethostname(),
                "host.fqdn": socket.getfqdn()}
开发者ID:cotyb,项目名称:ipopo,代码行数:33,代码来源:report.py

示例10: connect

def connect(host, port, ipv6=0, bind="0.0.0.0", bindport=0):
    if ipv6:
        af_inet = socket.AF_INET6
    else:
        af_inet = socket.AF_INET
    if not bindport:
        bindport = random.choice(range(40000, 50000))
    s = None
    for res in socket.getaddrinfo(bind, bindport, af_inet, socket.SOCK_STREAM):
        vhost = res[4]
        for res in socket.getaddrinfo(host, port, af_inet, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                s = socket.socket(af, socktype, proto)
            except socket.error, e:
                s = None;error=e
                continue
            try:
                s.bind(vhost)
                s.connect(sa)
            except socket.error, e:
                s.close()
                s = None;error=e
                continue
            break
开发者ID:tormaroe,项目名称:Ping-Ring,代码行数:25,代码来源:oddstr13.py

示例11: start

 def start(self):
     INFO("{} starting with pid: {}".format(self.name, self.pid))
     kill_processes(self.name, manager_logger)
     ck = ChildKiller(self.name, manager_logger, redis=True)
     ck.daemon = True
     ck.start()
     loc_addr = {addr[4][0] for addr in
                 socket.getaddrinfo('localhost', 80) +
                 socket.getaddrinfo(socket.getfqdn(), 80)}
     for single_repl in self.shard_list:
         for db_attr in single_repl:
             cfg_addr = {addr[4][0] for addr in
                 socket.getaddrinfo(db_attr['host'], 80)}
             if loc_addr & cfg_addr:
                 srv = RedisManager(db_attr, self.done_q)
                 srv.daemon = True
                 srv.start()
                 self.srvs.append(srv)
                 INFO('Redis Manager {} spawned'.format(db_attr))
     for _ in self.srvs:
         try:
             db_attr = self.done_q.get(timeout=INIT_WAIT_LIMIT)
             db_attr.pop('db')
             INFO('Redis Manager {} started'.format(db_attr))
         except Empty:
             ERROR("{}:: Unable to start all Redis Managers."
                 .format(self.name))
             sys.exit(1)
     for srv in self.srvs:
         srv.join()
     ck.join()
开发者ID:psusloparov,项目名称:RedisDistributedTasksSystem,代码行数:31,代码来源:run.py

示例12: port_to_tcp

def port_to_tcp(port=None):
    """Returns local tcp address for a given `port`, automatic port if `None`"""
    #address = 'tcp://' + socket.gethostbyname(socket.getfqdn())
    domain_name = socket.getfqdn()
    try:
        addr_list = socket.getaddrinfo(domain_name, None)
    except Exception:
        addr_list = socket.getaddrinfo('127.0.0.1', None)
    family, socktype, proto, canonname, sockaddr = addr_list[0]
    host = convert_ipv6(sockaddr[0])
    address =  'tcp://' + host
    if port is None:
        port = ()
    if not isinstance(port, int):
        # determine port automatically
        context = zmq.Context()
        try:
            socket_ = context.socket(zmq.REP)
            socket_.ipv6 = is_ipv6(address)
            port = socket_.bind_to_random_port(address, *port)
        except Exception:
            print('Could not connect to {} using {}'.format(address, addr_list))
            pypet_root_logger = logging.getLogger('pypet')
            pypet_root_logger.exception('Could not connect to {}'.format(address))
            raise
        socket_.close()
        context.term()
    return address + ':' + str(port)
开发者ID:SmokinCaterpillar,项目名称:pypet,代码行数:28,代码来源:helpful_functions.py

示例13: _is_local

 def _is_local(self, host):
     loc_addr = {addr[4][0] for addr in
                 socket.getaddrinfo('localhost', 80) +
                 socket.getaddrinfo(socket.getfqdn(), 80)}
     cfg_addr = {addr[4][0] for addr in
                 socket.getaddrinfo(host, 80)}
     return loc_addr & cfg_addr
开发者ID:psusloparov,项目名称:RedisDistributedTasksSystem,代码行数:7,代码来源:test_redis_manager.py

示例14: read_network

def read_network():
    netdict = {}
    netdict['class'] = "NETINFO"

    netdict['hostname'], netdict['ipaddr'], netdict['ip6addr'] = findHostByRoute()

    if netdict['hostname'] == "unknown":
        netdict['hostname'] = gethostname()
        if "." not in netdict['hostname']:
            netdict['hostname'] = socket.getfqdn()

    if netdict['ipaddr'] is None:
        try:
            list_of_addrs = getaddrinfo(netdict['hostname'], None)
            ipv4_addrs = filter(lambda x:x[0]==socket.AF_INET, list_of_addrs)
            # take first ipv4 addr
            netdict['ipaddr'] = ipv4_addrs[0][4][0]
        except:
            netdict['ipaddr'] = "127.0.0.1"

    if netdict['ip6addr'] is None:
        try:
            list_of_addrs = getaddrinfo(netdict['hostname'], None)
            ipv6_addrs = filter(lambda x:x[0]==socket.AF_INET6, list_of_addrs)
            # take first ipv6 addr
            netdict['ip6addr'] = ipv6_addrs[0][4][0]
        except:
            netdict['ip6addr'] = "::1"

    if netdict['ipaddr'] is None:
        netdict['ipaddr'] = ''
    if netdict['ip6addr'] is None:
        netdict['ip6addr'] = ''
    return netdict
开发者ID:aronparsons,项目名称:spacewalk,代码行数:34,代码来源:hardware.py

示例15: updatePublicAddress

    def updatePublicAddress(self):
        if self.config["address"] is not None:
            self.public_host = self.config["address"]
            self.public_ip = [addr[4][0] for addr in socket.getaddrinfo(self.public_host, None) if self._addrIsUsable(addr)][0]
        else:
            try:
                conn = urllib2.urlopen("http://ifconfig.me/all.json", timeout=3)
                data = json.loads(conn.read())
                self.raw_ip, self.raw_host = data["ip_addr"], data["remote_host"]
            except:
                log.err("Couldn't fetch remote IP and hostname")
                self.raw_host = socket.getfqdn()
                ips = [addr[4][0] for addr in socket.getaddrinfo(self.raw_host, None) if self._addrIsUsable(addr)]
                self.raw_ip = ips[0] if ips else "127.0.0.1"

            self.public_host = self.raw_host
            self.public_ip = self.raw_ip

        tcp = map(lambda p: int(p.split(":")[1]), filter(lambda p: p.startswith("tcp"), self.config["endpoints"]))
        if self.config["port"]:
            self.public_port = self.config["port"]
        elif tcp and 80 not in tcp:
            self.public_port = tcp[0]
        else:
            self.public_port = 80

        self.public_address = "http://{}:{:d}/".format(self.public_host, self.public_port) if self.public_port != 80 else "http://{}/".format(self.public_host)
开发者ID:fullcounter,项目名称:txoffer,代码行数:27,代码来源:txoffer.py


注:本文中的socket.getaddrinfo函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。