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


Python IPAddress.is_unicast方法代码示例

本文整理汇总了Python中netaddr.IPAddress.is_unicast方法的典型用法代码示例。如果您正苦于以下问题:Python IPAddress.is_unicast方法的具体用法?Python IPAddress.is_unicast怎么用?Python IPAddress.is_unicast使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在netaddr.IPAddress的用法示例。


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

示例1: get_ip_address

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
    def get_ip_address(self, test_address=None):
        """
        try to get global IP address from interface information.
        if failed, just return '127.0.0.1'

        :param str test_address: ip address str if test to check global ip.
                                  normally None.
        :return: global ip address if successed, or '127.0.0.1'
        """
        for iface_name in netifaces.interfaces():
            iface_data = netifaces.ifaddresses(iface_name)
            logging.debug('Interface: %s' % (iface_name, ))
            ifaces = []
            if netifaces.AF_INET in iface_data:
                ifaces += iface_data[netifaces.AF_INET]
            if netifaces.AF_INET6 in iface_data:
                ifaces += iface_data[netifaces.AF_INET6]
            for iface in ifaces:
                ip = iface['addr']
                ip = re.sub(r'\%.+$', '', ip)
                if test_address is not None:
                    ip = test_address
                addr = IPAddress(ip)
                if not addr.is_loopback() and addr.is_unicast() and\
                   not addr.is_private():
                    logging.debug('global ip %s', addr)
                    return ip
        logging.debug('no global ip')
        return '127.0.0.1'
开发者ID:utamaro,项目名称:StorjNet,代码行数:31,代码来源:encryption.py

示例2: _is_public

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
 def _is_public(self, ip):
     ip = IPAddress(ip)
     return ip.is_unicast() and not ip.is_private()
开发者ID:John-Lin,项目名称:nat,代码行数:5,代码来源:snat.py

示例3: test_is_public

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
def test_is_public():
    ip = IPAddress('62.125.24.5')
    assert ip.is_unicast() and not ip.is_private()
开发者ID:drkjam,项目名称:netaddr,代码行数:5,代码来源:test_ip_categories.py

示例4: has_public_ip

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
 def has_public_ip(self):
     ip = IPAddress(self.ip)
     return ip.is_unicast() and not ip.is_private()
开发者ID:fiware-cybercaptor,项目名称:cybercaptor-data-extraction,代码行数:5,代码来源:topology.py

示例5: fifoReader

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
def fifoReader(infile, q, exitSignal):
    sleeptime=0.5
    maxSleeptime=1.0

    while True:
        try:
            if exitSignal.is_set(): break

            line=infile.readline()

            if not line:
                time.sleep(1)
                continue

            if line=='ENDOFFILE':
                break

            try:
                spl=line.split()
                timestamp, queriedName, clientID, ipv4 = spl
            except:
                continue
            else:
                if not '.' in queriedName:
                    continue
                try:
                    addr=IPAddress(ipv4)
                except netaddr.AddrFormatError:
                    continue
                else:
                    if (addr.is_unicast() and
                        not addr.is_private() and
                        not addr.is_reserved() and
                        not addr.is_loopback()):

                        try:
                            timestamp=int(timestamp)
                        except ValueError:
                            continue
                        else:
                            data = ((queriedName, clientID, [addr]),
                                    timestamp)
                            queued=False
                            while not queued:
                                try:
                                    q.put_nowait(data)
                                except Queue.Full:
                                    # we saturated the queue, let's give the reading
                                    # process some time to empty it again, where we don't
                                    # try to put something in the queue and thereby lock it
                                    # continuously
                                    time.sleep(sleeptime)

                                    if q.empty():
                                        sleeptime*=0.5
                                    elif q.qsize() >= q._maxsize:
                                        sleeptime*=2
                                        if sleeptime>maxSleeptime:
                                            sleeptime=maxSleeptime
                                else:
                                    queued=True

        except KeyboardInterrupt:
            break

    q.put(None)
开发者ID:anderasberger,项目名称:pydnsmap,代码行数:68,代码来源:dnsmapIO.py

示例6: pcapReader

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
def pcapReader(q, exitSignal, infile=None, interface=None, thrsh=0):

    if not infile and not interface:
        # FIXME: write warning here
        return

    if infile:
        pc=pcap.pcapObject()
        try:
            pc.open_offline(infile)
        except IOError:
            #log("could not open pcap interface "+str(input_interface)+"\n")
            pass

    if interface:
        pc=pcap.pcapObject()
        try:
            #pc.open_live(interface, snaplen, promisc, read_timeout)
            pc.open_live(interface, 1600, 0, 100)
        except IOError:
            #log("could not open pcap interface "+str(input_interface)+"\n")
            pass
        except Exception:
            # most likely we got no permission to open the interface
            sys.stderr.write('could not open interface. insufficient '
                'permissions?\n')
            q.put(None)
            return

    pc.setfilter('udp', 0, 0)
    basets=0
    newMappings=dict()

    while True:
        if exitSignal.is_set():
            break

        try:
            packet=pc.next()
            if not packet:
                if infile:
                    # end of file
                    break
                elif interface:
                    # read timeout
                    continue

            payload=packet[1]
            timestamp=int(packet[2])

            # make sure we are dealing with IP traffic
            # ref: http://www.iana.org/assignments/ethernet-numbers
            try: eth = dpkt.ethernet.Ethernet(payload)
            except: continue
            if eth.type != 2048: continue

            # make sure we are dealing with UDP
            # ref: http://www.iana.org/assignments/protocol-numbers/
            try: ip = eth.data
            except: continue
            if ip.p != 17: continue

            # filter on UDP assigned ports for DNS
            # ref: http://www.iana.org/assignments/port-numbers
            try: udp = ip.data
            except: continue
            if udp.sport != 53 and udp.dport != 53: continue

            # make the dns object out of the udp data and check for it being a RR (answer)
            # and for opcode QUERY (I know, counter-intuitive)
            try: dns = dpkt.dns.DNS(udp.data)
            except: continue
            if dns.qr != dpkt.dns.DNS_R: continue
            if dns.opcode != dpkt.dns.DNS_QUERY: continue
            if dns.rcode != dpkt.dns.DNS_RCODE_NOERR: continue
            if len(dns.an) < 1: continue
            if len(dns.qd) == 0: continue

            aRecords=set()
            queriedName=dns.qd[0].name

            if not '.' in queriedName:
                continue

            #lastCname=queriedName
            for answer in dns.an:
                """
                FIXME: this doesn't work for multiple queries in one DNS packet
                """
                #if answer.type == dpkt.dns.DNS_CNAME:
                #    lastCname=answer.cname
                if answer.type == dpkt.dns.DNS_A:
                    ip=socket.inet_ntoa(answer.rdata)
                    try:
                        addr=IPAddress(ip)
                    except netaddr.AddrFormatError:
                        continue
                    else:
                        if (addr.is_unicast() and
                            not addr.is_private() and
#.........这里部分代码省略.........
开发者ID:anderasberger,项目名称:pydnsmap,代码行数:103,代码来源:dnsmapIO.py

示例7: ping

# 需要导入模块: from netaddr import IPAddress [as 别名]
# 或者: from netaddr.IPAddress import is_unicast [as 别名]
    def ping(self, targets=list(), filename=str(), status=str(), notDNS=False,
        elapsed=False
    ):
        """
        Attempt to ping a list of hosts or networks (can be a single host)
        :param targets: List - Name(s) or IP(s) of the host(s).
        :param filename: String - name of the file containing hosts to ping
        :param status: String - if one of ['alive', 'dead', 'noip'] then only
        return results that have that status. If this is not specified,
        then all results will be returned.
        :param notDNS: Bolean - If True turn on use of -A option for fping for
        not use dns resolve names. Default is False.
        :param elapsed: Bolean - If True turn on use of -e option for fping for
        show elapsed time on return packets. Default is False.
        :return: Type and results depends on whether status is specified:
                 if status == '': return dict: {targets: results}
                 if status != '': return list: targets if targets == status
        """

        if targets and filename:
            raise SyntaxError("You must specify only one of either targets=[] "
                              "or filename=''.")
        elif not targets and not filename:
            raise SyntaxError("You must specify either a list of targets or "
                              "filename='', but not both.")
        elif filename:
            targets = self.read_file(filename)

        my_targets = {'hosts': [], 'nets': []}
        addresses = []

        # Check for valid networks and add hosts and nets to my_targets
        for target in targets:
            # Targets may include networks in the format "network mask", or,
            # a file could contain multiple hosts or IP's on a single line.
            if len(target.split()) > 1:
                target_items = target.split()
                for item in target_items:
                    try:
                        ip = IPAddress(item)
                        # If it is an IPv4 address or mask put in in addresses
                        if ip.version == 4:
                            addresses.append(str(ip))
                    except AddrFormatError:
                        # IP Address not detected, so assume it's a host name
                        my_targets['hosts'].append(item)
                    except ValueError:
                        # CIDR network detected
                        net = IPNetwork(item)
                        # Make sure it is a CIDR address acceptable to fping
                        if net.ip.is_unicast() and net.version == 4 and \
                                net.netmask.netmask_bits() in range(8, 31):
                            my_targets['nets'].append(target_items[0])
                        else:
                            msg = str(str(net) + ':Only IPv4 unicast addresses'
                                      ' with bit masks\n               '
                                      ' from 8 to 30 are supported.')
                            raise AttributeError(msg)
                # Iterate over the IP strings in addresses
                while len(addresses) > 1:
                    ip = IPAddress(addresses[0])
                    mask = IPAddress(addresses[1])
                    # Test to see if IP is unicast, and mask is an actual mask
                    if ip.is_unicast() and mask.is_netmask():
                        net = IPNetwork(str(ip) + '/' + str(
                            mask.netmask_bits()))
                        # Convert ip and mask to CIDR and remove from addresses
                        my_targets['nets'].append(str(net.cidr))
                        addresses.pop(0)
                        addresses.pop(0)
                    elif ip.is_unicast() and not ip.is_netmask():
                        # mask was not a mask so only remove IP and start over
                        my_targets['hosts'].append(str(ip))
                        addresses.pop(0)
                # There could be one more item in addresses, so check it
                if addresses:
                    ip = IPAddress(addresses[0])
                    if ip.is_unicast() and not ip.is_netmask():
                        my_targets['hosts'].append(addresses[0])
                        addresses.pop()
            # target has only one item, so check it
            else:
                try:
                    ip = IPAddress(target)
                    if ip.version == 4 and ip.is_unicast() and \
                            not ip.is_netmask():
                        my_targets['hosts'].append(target)
                    else:
                        msg = str(target + 'Only IPv4 unicast addresses are '
                                  'supported.')
                        raise AttributeError(msg)
                except AddrFormatError:
                    # IP Address not detected, so assume it's a host name
                    my_targets['hosts'].append(target)
                except ValueError:
                    # CIDR network detected
                    net = IPNetwork(target)
                    if net.ip.is_unicast() and net.version == 4 and \
                            net.netmask.netmask_bits() in range(8, 31):
                        my_targets['nets'].append(target)
#.........这里部分代码省略.........
开发者ID:rctorr,项目名称:fping.py,代码行数:103,代码来源:fping.py


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