• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.inet_ntop函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _ParseProcIgmp

  def _ParseProcIgmp(self):
    """Returns a list of current IGMP group memberships.

    /proc/net/igmp uses an unusual format:
    Idx Device    : Count Querier       Group    Users Timer    Reporter
    1   lo        :     1      V3
                                010000E0     1 0:00000000           0
    2   eth0      :     1      V3
                                010000E0     1 0:00000000           0
    010000E0 is the IP multicast address as a hex number, and always
    big endian.
    """
    igmps = set()
    with open(PROCNETIGMP, 'r') as f:
      for line in f:
        result = IGMPREGEX.match(line)
        if result is not None:
          igmp = result.group(1).strip()
          igmps.add(socket.inet_ntop(
              socket.AF_INET, struct.pack('<L', int(igmp, 16))))
    with open(PROCNETIGMP6, 'r') as f:
      for line in f:
        result = IGMP6REGEX.match(line)
        if result is not None:
          igmp = result.group(1).strip()
          ip6 = ':'.join([igmp[0:4], igmp[4:8], igmp[8:12], igmp[12:16],
                          igmp[16:20], igmp[20:24], igmp[24:28], igmp[28:]])
          igmps.add(socket.inet_ntop(socket.AF_INET6,
                                     socket.inet_pton(socket.AF_INET6, ip6)))
    return list(igmps)
开发者ID:Benozo,项目名称:catawampus,代码行数:30,代码来源:stbservice.py


示例2: send_pcapbreak

def send_pcapbreak(pkt, stopped):

    if stopped.isSet():
        return

    iph, tcph, tcpo, payload = parse_headers(pkt)
    ipdst_str = socket.inet_ntop(socket.AF_INET, struct.pack('!L', iph.dstaddr))
    ipsrc_str = socket.inet_ntop(socket.AF_INET, struct.pack('!L', iph.srcaddr))

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
	s.bind(('',tcph.srcport))
        s.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, 1)
    except (socket.error, socket.gaierror):
	print "Warn: cannot operate sending packets to break pcap loop"
	return

    retry = 0.4
    for i in range(0, 5):
        s.sendto("*", (ipdst_str, PCAP_BREAK_DPORT))
	stopped.wait(retry)
	if stopped.isSet():
	    break
	retry *= 2
    s.close()

#    if stopped.isSet() is False:
#        print "Warn: break packet is not handled"
    return
开发者ID:PerthCharles,项目名称:tcpexposure,代码行数:29,代码来源:tcpsrlib.py


示例3: ping_node

	def ping_node(self, node):
		task = self.taskman.new_task()

		msgout = codec_pb2.MsgDHTMisc()
		msgout.request_id = task.task_id

		if len(node.ip) == 4:
			node_ip = socket.inet_ntop(socket.AF_INET, node.ip)
		else:
			node_ip = socket.inet_ntop(socket.AF_INET6, node.ip)
		addr_tup = (node_ip, node.port)

		task.addr = addr_tup
		task.msg_start = msgout

		# clamp to "1s ... (rtt * 10) ... 15s" range
		min_timeout = datetime.timedelta(seconds=1)
		max_timeout = datetime.timedelta(seconds=15)
		if node.rtt is None:
			task.timeout = max_timeout
		else:
			task.timeout = node.rtt * 10
			if task.timeout > max_timeout:
				task.timeout = max_timeout
			if task.timeout < min_timeout:
				task.timeout = min_timeout

		task.timeout_actor = ping_node_timeout
		task.timeout_args = [self, node]

		self.send_message("ping", msgout, addr_tup)
开发者ID:BuloZB,项目名称:smartcoin,代码行数:31,代码来源:dht.py


示例4: extractRecord

def extractRecord(resolver, name, answers, level=10):
    if not level:
        return None
    if hasattr(socket, 'inet_ntop'):
        for r in answers:
            if r.name == name and r.type == dns.A6:
                return socket.inet_ntop(socket.AF_INET6, r.payload.address)
        for r in answers:
            if r.name == name and r.type == dns.AAAA:
                return socket.inet_ntop(socket.AF_INET6, r.payload.address)
    for r in answers:
        if r.name == name and r.type == dns.A:
            return socket.inet_ntop(socket.AF_INET, r.payload.address)
    for r in answers:
        if r.name == name and r.type == dns.CNAME:
            result = extractRecord(
                resolver, r.payload.name, answers, level - 1)
            if not result:
                return resolver.getHostByName(
                    str(r.payload.name), effort=level - 1)
            return result
    # No answers, but maybe there's a hint at who we should be asking about
    # this
    for r in answers:
        if r.type == dns.NS:
            from twisted.names import client
            r = client.Resolver(servers=[(str(r.payload.name), dns.PORT)])
            return r.lookupAddress(str(name)
                ).addCallback(
                    lambda records: extractRecord(
                        r, name,
                        records[_ANS] + records[_AUTH] + records[_ADD],
                        level - 1))
开发者ID:hensing,项目名称:twisted,代码行数:33,代码来源:common.py


示例5: printResponse

    def printResponse(self, message):
        if message.HasField('response'):
            response = message.response
            policystr = ''
            if response.HasField('appliedPolicy') and response.appliedPolicy:
                policystr = ', Applied policy: ' + response.appliedPolicy

            tagsstr = ''
            if response.tags:
                tagsstr = ', Tags: ' + ','.join(response.tags)

            rrscount = len(response.rrs)

            print("- Response Code: %d, RRs: %d%s%s" % (response.rcode,
                                                      rrscount,
                                                      policystr,
                                                      tagsstr))

            for rr in response.rrs:
                rrclass = 1
                rdatastr = ''
                if rr.HasField('class'):
                    rrclass = getattr(rr, 'class')
                rrtype = rr.type
                if (rrclass == 1 or rrclass == 255) and rr.HasField('rdata'):
                    if rrtype == 1:
                        rdatastr = socket.inet_ntop(socket.AF_INET, rr.rdata)
                    elif rrtype == 28:
                        rdatastr = socket.inet_ntop(socket.AF_INET6, rr.rdata)

                print("\t - %d, %d, %s, %d, %s" % (rrclass,
                                                   rrtype,
                                                   rr.name,
                                                   rr.ttl,
                                                   rdatastr))
开发者ID:ColMelvin,项目名称:pdns,代码行数:35,代码来源:ProtobufLogger.py


示例6: unpack_host

def unpack_host(host):
    #fp=open("host.txt",'w+b')
    #fp.write(host+"\n")
    if len(host) == 4:
        return socket.inet_ntop(socket.AF_INET, host)
    elif len(host) == 16: 
        return socket.inet_ntop(socket.AF_INET6, host)
开发者ID:IntegrationEnvironment,项目名称:DHT-woodworm,代码行数:7,代码来源:utils.py


示例7: routes

def routes ():
	links = {}
	for ifi in Link.getLinks():
		links[ifi.index] = ifi.attributes.get(Link.Type.Attribute.IFLA_IFNAME).strip('\0')

	print('Kernel IP routing table')
	print('%-18s %-18s %-18s %-7s %s' % ('Destination','Genmask','Gateway','Metric','Iface'))

	for route in Network.getRoutes():
		if route.family != socket.AF_INET:
			continue

		if route.type not in (Network.Type.Type.RTN_LOCAL,Network.Type.Type.RTN_UNICAST):
			continue

		if route.src_len == 32:
			continue

		destination = route.attributes.get(Network.Type.Attribute.RTA_DST)
		gateway = route.attributes.get(Network.Type.Attribute.RTA_GATEWAY)

		oif = ord(route.attributes.get(Network.Type.Attribute.RTA_OIF)[0])
		metric = ord(route.attributes.get(Network.Type.Attribute.RTA_PRIORITY,'\0')[0])

		dst = '%s' % socket.inet_ntop(route.family, destination) if destination else ''
		gw  = '%s' % socket.inet_ntop(route.family, gateway) if gateway else '0.0.0.0'
		mask = NetMask.CIDR[route.src_len]
		iface = links[oif]

		print('%-18s %-18s %-18s %-7d %-s' % (dst or '0.0.0.0',mask,gw,metric,iface))
开发者ID:Exa-Networks,项目名称:exabgp,代码行数:30,代码来源:netlink.py


示例8: data_received

    def data_received(self, data):

        if self.state == self.INIT:
            assert data[0] == 0x05
            # server -> client. VER | METHOD
            self.transport.write(pack('!BB', 0x05, 0x00))  # no auth
            self.state = self.HOST

        elif self.state == self.HOST:
            # socks request info. VER | CMD | RSV | ATYP | SDT.ADDR | DST.PORT
            ver, cmd, rsv, atype = data[:4]
            assert ver == 0x05 and cmd == 0x01

            if atype == 3:    # domain
                length = data[4]
                hostname, nxt = data[5:5 + length], 5 + length
            elif atype == 1:  # ipv4
                hostname, nxt = socket.inet_ntop(socket.AF_INET, data[4:8]), 8
            elif atype == 4:  # ipv6
                hostname, nxt = socket.inet_ntop(socket.AF_INET6, data[4:20]), 20
            else:
                logging.warn('addr_type not suport')
                return

            port = unpack('!H', data[nxt:nxt + 2])[0]

            logging.info('request connect to {}:{}'.format(hostname, port))
            # 连接proxyserver
            asyncio.ensure_future(self.connect(hostname, port))
            self.state = self.DATA

        elif self.state == self.DATA:
            self.client_transport.write(data)
开发者ID:lyncir,项目名称:s5proxy,代码行数:33,代码来源:client.py


示例9: from_bytes

 def from_bytes(cls, b):
     services, host, port = struct.unpack('>Q16sH', b)
     if host.startswith(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'):
         host = socket.inet_ntop(socket.AF_INET, host[-4:])
     else:
         host = socket.inet_ntop(socket.AF_INET6, host)
     return cls(services, host, port)
开发者ID:TheKysek,项目名称:MiNode,代码行数:7,代码来源:structure.py


示例10: read_address

 def read_address(self, fd):
   """ read a warts-style ip/mac address """
   length = WartsReader.read_uint8_t(self.fd)
   addr = 0
   typ = 0
   # an embedded (non-referenced) address
   if length != 0:
     typ = WartsReader.read_uint8_t(fd)
     addr = self.fd.read(length)
     addr_id = len(self.address_ref)
     self.address_ref[addr_id] = addr 
   # a referenced address
   else:
     addr_id = WartsReader.read_uint32_t(fd)
     try:
       addr = self.address_ref[addr_id]
     except:
       print "Die: couldn't find referenced address %d" % addr_id
       sys.exit(-1)
   if typ == 0:
     if len(addr) == 4: typ = 1
     if len(addr) == 16: typ = 2
   if typ == 1:
     return socket.inet_ntop(socket.AF_INET, addr)
   elif typ == 2:
     return socket.inet_ntop(socket.AF_INET6, addr)
   else:
     print "Addr type:", typ, "not implemented"
     assert False
开发者ID:bugamn,项目名称:scamper,代码行数:29,代码来源:sc_warts.py


示例11: ParseBmpPeerUp

def ParseBmpPeerUp(message, peer_flags, verbose=False):
    """Parse a BMP V3 Peer Up message.

  Args:
    header: array containing BMP peer up message.
    peer_flags: from the per-peer header.
    verbose: be chatty, or not.

  Returns:
    A list of strings to print.

  Raises:
    ValueError: an unexpected value was found in the message
  """

    indent_str = indent.IndentLevel(indent.BMP_CONTENT_INDENT)
    print_msg = []
    offset = 0

    if peer_flags & PEER_FLAG_IPV6:
        loc_addr = socket.inet_ntop(socket.AF_INET6, message[offset : offset + 16])
    else:
        loc_addr = socket.inet_ntop(socket.AF_INET, message[offset + 12 : offset + 16])
    offset += 16
    loc_port, rem_port = struct.unpack_from(">HH", message, offset)

    print_msg.append("%sloc_addr %s, loc_port %d, rem_port %d\n" % (indent_str, loc_addr, loc_port, rem_port))
    return print_msg
开发者ID:craigesmith,项目名称:bmpreceiver,代码行数:28,代码来源:BMP.py


示例12: show_dns

def show_dns(self, family):
    if (family == socket.AF_INET):
       ip_cfg = self.get_ip4_config()
    else:
       ip_cfg = self.get_ip6_config()

    if ip_cfg is None:
        print("None")
        return

    if (family == socket.AF_INET):
        print ("Domains: %s") % (ip_cfg.get_domains())
        print ("Searches: %s") % (ip_cfg.get_searches())
        print("Nameservers:")
        nameservers = ip_cfg.get_nameservers()
        for dns in nameservers:
            print socket.inet_ntop(family, struct.pack("=I", dns))
    else:
        print ("Domains: %s") % (ip_cfg.get_domains())
        print ("Searches: %s") % (ip_cfg.get_searches())
        print("Nameservers:")
        num = ip_cfg.get_num_nameservers()
        for i in range(0,num):
           dns = ip_cfg.get_nameserver(i)
           print socket.inet_ntop(family, dns)
开发者ID:heftig,项目名称:NetworkManager,代码行数:25,代码来源:get_ips.py


示例13: show_routes

def show_routes(self, family):
    if (family == socket.AF_INET):
       ip_cfg = self.get_ip4_config()
    else:
       ip_cfg = self.get_ip6_config()

    if ip_cfg is None:
        print("None")
        return

    nm_routes = ip_cfg.get_routes()
    if len(nm_routes) == 0:
        print("None")
        return

    for nm_route in nm_routes:
        dest = nm_route.get_dest()
        prefix = nm_route.get_prefix()
        next_hop = nm_route.get_next_hop()
        metric = nm_route.get_metric()

        if (family == socket.AF_INET):
            dest_struct = struct.pack("=I", dest)
            next_hop_struct = struct.pack("=I", next_hop)
        else:
            dest_struct = dest
            next_hop_struct = next_hop
        print("%s/%d  %s  %d") % (socket.inet_ntop(family, dest_struct),
                                  prefix,
                                  socket.inet_ntop(family, next_hop_struct),
                                  metric)
开发者ID:heftig,项目名称:NetworkManager,代码行数:31,代码来源:get_ips.py


示例14: show_addresses

def show_addresses(self, family):
    if (family == socket.AF_INET):
       ip_cfg = self.get_ip4_config()
    else:
       ip_cfg = self.get_ip6_config()

    if ip_cfg is None:
        print("None")
        return

    nm_addresses = ip_cfg.get_addresses()
    if len(nm_addresses) == 0:
        print("None")
        return

    for nm_address in nm_addresses:
        addr = nm_address.get_address()
        prefix = nm_address.get_prefix()
        gateway = nm_address.get_gateway()

        if (family == socket.AF_INET):
            addr_struct = struct.pack("=I", addr)
            gateway_struct = struct.pack("=I", gateway)
        else:
            addr_struct = addr
            gateway_struct = gateway
        print("%s/%d  %s") % (socket.inet_ntop(family, addr_struct),
                              prefix,
                              socket.inet_ntop(family, gateway_struct))
开发者ID:heftig,项目名称:NetworkManager,代码行数:29,代码来源:get_ips.py


示例15: get_random_cidr

def get_random_cidr(mask=None, af='v4'):
    ''' Generate a random subnet based on netmask and address family '''
    if not is_valid_af(af=af):
        raise ValueError("Address family not supported %s" % af)
    if mask is None:
        mask = SUBNET_MASK[af]['default']
    if type(mask) is int:
        mask = str(mask)
    if not is_valid_subnet_mask(plen=mask, af=af):
        raise ValueError("Invalid subnet mask %s for af %s" % (mask, af))
    while (True):
        if af == 'v6':
            min = 0x2001000000000000
            max = 0x3fffffffffffffff
            address = socket.inet_ntop(socket.AF_INET6,
                                       struct.pack('>2Q',
                                                   random.randint(min, max),
                                                   random.randint(0, 2 ** 64)))
        elif af == 'v4':
            address = socket.inet_ntop(socket.AF_INET,
                                       struct.pack('>I',
                                                   random.randint(2 ** 24, 2 ** 32)))
        if is_reserved_address(address):
            continue
        if is_valid_address(address):
            return '%s/%s' % (str(IPNetwork(address + '/' + mask).network), mask)
开发者ID:vedujoshi,项目名称:contrail-test-ci,代码行数:26,代码来源:util.py


示例16: __init__

    def __init__(self, address, packet):
        """
        Initialize a usagepacket from a binary string containing the UDP
        packet contents.

        Arguments:
        self -- The new usagepacket.usagepacket object
        packet -- The binary packet contents

        Returns:
        New IPTimeMonitorPacket

        """
        UsagePacket.__init__(self, address, packet)
        packdata = self.unpack("qB")
        time_sent_millis = packdata[0]
        time_sent = time_sent_millis / 1000
        frac_secs = time_sent_millis - int(time_sent_millis)
        send_time = list(time.gmtime(time_sent))[0:6]
        send_time[5] += frac_secs
        self.send_time = tuple(send_time)
        address_form = packdata[1]
        if address_form == 4:
            address_data = self.unpack("4B")
            self.ip_address = socket.inet_ntop(
                            socket.AF_INET, struct.pack('4B', *address_data))
        elif address_form == 6:
            address_data = self.unpack("16B")
            self.ip_address = socket.inet_ntop(
                            socket.AF_INET6, struct.pack('16B', *address_data))
开发者ID:bbockelm,项目名称:globus-toolkit,代码行数:30,代码来源:iptimemonitorpacket.py


示例17: parseIP6

def parseIP6(data):

    ip6Loc = data
    ip6 = {}

    ip6.update({'version':ip6Loc.v})
    ip6.update({'destination_address':socket.inet_ntop(socket.AF_INET6, ip6Loc.dst)})
    ip6.update({'source_address':socket.inet_ntop(socket.AF_INET6, ip6Loc.src)})
    ip6.update({'hop_limit':ip6Loc.hlim})
    ip6.update({'payload_length':ip6Loc.plen})
    ip6.update({'next':ip6Loc.nxt})
    ip6.update({'flow_label':ip6Loc.flow})
    
    next = ip6['next']
    extHeader = []

    while next in [0, 43, 44, 51, 50, 60, 135, 59]:
        header = parseExtensionHeader(ip6Loc.data)
        extHeader.append(header)

        if type(ip6Loc.data) not in [dpkt.ip6.IP6OptsHeader,dpkt.ip6.IP6HopOptsHeader,  dpkt.ip6.IP6DstOptsHeader, dpkt.ip6.IP6RoutingHeader, dpkt.ip6.IP6FragmentHeader, dpkt.ip6.IP6AHHeader, dpkt.ip6.IP6ESPHeader]:
            break

        ip6Loc = ip6Loc.data
        next = ip6Loc.nxt

    if len(extHeader) > 0:
        ip6.update({'extensionHeader':extHeader})

    ip6.update({'data':ip6Loc.data})

    return ip6
开发者ID:Egomania,项目名称:TraViSy,代码行数:32,代码来源:pcapParser.py


示例18: _unquote_host

	def _unquote_host(self, host):
		# IPv6 / IPvFuture
		if host.startswith(b'[') and host.endswith(b']'):
			host = host[1:-1]
			try:
				return u'[%s]' % inet_ntop(AF_INET6, inet_pton(AF_INET6, host)).decode('ascii')
			except SocketError:
				# IPvFuture
				if host.startswith(b'v') and b'.' in host and host[1:].split('.', 1)[0].isdigit():
					try:
						return u'[%s]' % host.decode('ascii')
					except UnicodeDecodeError:
						raise InvalidURI(_('Invalid IPvFuture address: must be ASCII.'))
				raise InvalidURI(_('Invalid IP address in URI.'))
		# IPv4
		if all(x.isdigit() for x in host.split(b'.')):
			try:
				return inet_ntop(AF_INET, inet_pton(AF_INET, host)).decode('ascii')
			except SocketError:
				raise InvalidURI(_('Invalid IPv4 address in URI.'))

		if host.strip(Percent.UNRESERVED + Percent.SUB_DELIMS + b'%'):
			raise InvalidURI(_('Invalid URI host.'))

		# DNS hostname
		host = self.unquote(host)
		try:
			return host.encode('ascii').decode('idna').lower()
		except UnicodeError:
			raise InvalidURI(_('Invalid host.'))
开发者ID:pombredanne,项目名称:httoop,代码行数:30,代码来源:uri.py


示例19: recv_udp

 def recv_udp(listener, bufsize):
     debug3('Accept UDP using socket_ext recvmsg.\n')
     srcip, data, adata, flags = listener.recvmsg(
         (bufsize,), socket.CMSG_SPACE(24))
     dstip = None
     family = None
     for a in adata:
         if a.cmsg_level == socket.SOL_IP and a.cmsg_type == IP_ORIGDSTADDR:
             family, port = struct.unpack('=HH', a.cmsg_data[0:4])
             port = socket.htons(port)
             if family == socket.AF_INET:
                 start = 4
                 length = 4
             else:
                 raise Fatal("Unsupported socket type '%s'" % family)
             ip = socket.inet_ntop(
                 family, a.cmsg_data[start:start + length])
             dstip = (ip, port)
             break
         elif a.cmsg_level == SOL_IPV6 and a.cmsg_type == IPV6_ORIGDSTADDR:
             family, port = struct.unpack('=HH', a.cmsg_data[0:4])
             port = socket.htons(port)
             if family == socket.AF_INET6:
                 start = 8
                 length = 16
             else:
                 raise Fatal("Unsupported socket type '%s'" % family)
             ip = socket.inet_ntop(
                 family, a.cmsg_data[start:start + length])
             dstip = (ip, port)
             break
     return (srcip, dstip, data[0])
开发者ID:AdamIsrael,项目名称:sshuttle,代码行数:32,代码来源:client.py


示例20: deserialize_network_address

    def deserialize_network_address(self, data, has_timestamp=False):
        timestamp = None
        if has_timestamp:
            timestamp = struct.unpack("<I", data.read(4))[0]

        try:
            services = struct.unpack("<Q", data.read(8))[0]
        except struct.error as err:
            raise ReadError(err)

        _ipv6 = data.read(12)
        _ipv4 = data.read(4)
        port = struct.unpack(">H", data.read(2))[0]

        ipv6 = socket.inet_ntop(socket.AF_INET6, _ipv6 + _ipv4)
        ipv4 = socket.inet_ntop(socket.AF_INET, _ipv4)

        if ipv4 in ipv6:
            ipv6 = ""  # use ipv4
        else:
            ipv4 = ""  # use ipv6

        return {
            'timestamp': timestamp,
            'services': services,
            'ipv6': ipv6,
            'ipv4': ipv4,
            'port': port,
        }
开发者ID:9cat,项目名称:bitnodes,代码行数:29,代码来源:protocol.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.inet_pton函数代码示例发布时间:2022-05-27
下一篇:
Python socket.inet_ntoa函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap