Python socket 模块,inet_ntop() 实例源码

我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用socket.inet_ntop()

项目:trip    作者:littlecodersh    | 项目源码 | 文件源码
def _read_socks5_address(self):
        atyp = yield self.read_bytes(1)
        if atyp == b"\x01":
            data = yield self.read_bytes(4)
            addr = socket.inet_ntoa(data)
        elif atyp == b"\x03":
            length = yield self.read_bytes(1)
            addr = yield self.read_bytes(length)
        elif atyp == b"\x04":
            data = yield self.read_bytes(16)
            addr = socket.inet_ntop(socket.AF_INET6, data)
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        data = yield self.read_bytes(2)
        port = struct.unpack(">H", data)[0]
        raise gen.Return((addr, port))
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def in6_getifaddr():
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = []
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      ret = []
      while p:
        a = p.contents.addresses
        while a:
          if a.contents.addr.contents.sa_family == socket.AF_INET6:
            ap = a.contents.addr
            val = cast(ap, POINTER(sockaddr_in6))
            addr = socket.inet_ntop(socket.AF_INET6, bytes(val.contents.sin6_addr[:]))
            scope = scapy.utils6.in6_getscope(addr)
            ret.append((addr, scope, p.contents.name.decode('ascii')))
          a = a.contents.next
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs)
项目:fdslight    作者:fdslight    | 项目源码 | 文件源码
def calc_subnet(ipaddr, prefix, is_ipv6=False):
    if is_ipv6 and prefix == 128: return ipaddr
    if not is_ipv6 and prefix == 32: return ipaddr

    q = int(prefix / 8)
    r = prefix % 8

    if is_ipv6:
        byte_ipaddr = socket.inet_pton(socket.AF_INET6, ipaddr)
        results = list(bytes(16))
    else:
        byte_ipaddr = socket.inet_pton(socket.AF_INET, ipaddr)
        results = list(bytes(4))

    results[0:q] = byte_ipaddr[0:q]
    v = 0
    for n in range(r + 1):
        if n == 0: continue
        v += 2 ** (8 - n)

    results[q] = byte_ipaddr[q] & v
    if is_ipv6:
        return socket.inet_ntop(socket.AF_INET6, bytes(results))
    else:
        return socket.inet_ntop(socket.AF_INET, bytes(results))
项目:python-cookbook-3rd    作者:tuanavu    | 项目源码 | 文件源码
def cidr_range(cidr_address):
    family = AF_INET6 if ':' in cidr_address else AF_INET
    address, maskstr = cidr_address.split('/')
    maskbits = int(maskstr)

    # Parse the supplied address into bytes
    addr_bytes = inet_pton(family, address)

    # Calculate number of address bytes and mask bits
    addr_len = len(addr_bytes)
    numaddrs = 2**(addr_len*8 - maskbits)
    mask = -numaddrs

    # Generate addresses
    addr = int.from_bytes(addr_bytes, 'big') & mask
    for n in range(numaddrs):
        yield inet_ntop(family, (addr+n).to_bytes(addr_len, 'big'))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def testStringToIPv4(self):
        if not hasattr(socket, 'inet_ntop'):
            return # No inet_ntop() on this platform
        from socket import inet_ntoa as f, inet_ntop, AF_INET
        g = lambda a: inet_ntop(AF_INET, a)
        assertInvalid = lambda func,a: self.assertRaises(
            (socket.error, ValueError), func, a
        )

        self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
        self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
        assertInvalid(f, b'\x00' * 3)
        assertInvalid(f, b'\x00' * 5)
        assertInvalid(f, b'\x00' * 16)

        self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
        assertInvalid(g, b'\x00' * 3)
        assertInvalid(g, b'\x00' * 5)
        assertInvalid(g, b'\x00' * 16)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def in6_getifaddr():
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = []
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      ret = []
      while p:
        a = p.contents.addresses
        while a:
          if a.contents.addr.contents.sa_family == socket.AF_INET6:
            ap = a.contents.addr
            val = cast(ap, POINTER(sockaddr_in6))
            addr = socket.inet_ntop(socket.AF_INET6, bytes(val.contents.sin6_addr[:]))
            scope = scapy.utils6.in6_getscope(addr)
            ret.append((addr, scope, p.contents.name.decode('ascii')))
          a = a.contents.next
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def testStringToIPv6(self):
        try:
            from socket import inet_ntop, AF_INET6, has_ipv6
            if not has_ipv6:
                self.skipTest('IPv6 not available')
        except ImportError:
            self.skipTest('could not import needed symbols from socket')
        f = lambda a: inet_ntop(AF_INET6, a)

        self.assertEqual('::', f('\x00' * 16))
        self.assertEqual('::1', f('\x00' * 15 + '\x01'))
        self.assertEqual(
            'aef:b01:506:1001:ffff:9997:55:170',
            f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
        )

    # XXX The following don't test module-level functionality...
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def testStringToIPv6(self):
        try:
            from socket import inet_ntop, AF_INET6, has_ipv6
            if not has_ipv6:
                self.skipTest('IPv6 not available')
        except ImportError:
            self.skipTest('could not import needed symbols from socket')
        f = lambda a: inet_ntop(AF_INET6, a)

        self.assertEqual('::', f('\x00' * 16))
        self.assertEqual('::1', f('\x00' * 15 + '\x01'))
        self.assertEqual(
            'aef:b01:506:1001:ffff:9997:55:170',
            f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
        )

    # XXX The following don't test module-level functionality...
项目:scapy-bpf    作者:guedou    | 项目源码 | 文件源码
def in6_getifaddr():
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = []
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      ret = []
      while p:
        a = p.contents.addresses
        while a:
          if a.contents.addr.contents.sa_family == socket.AF_INET6:
            ap = a.contents.addr
            val = cast(ap, POINTER(sockaddr_in6))
            addr = socket.inet_ntop(socket.AF_INET6, str(val.contents.sin6_addr[:]))
            scope = scapy.utils6.in6_getscope(addr)
            ret.append((addr, scope, p.contents.name.decode('ascii')))
          a = a.contents.next
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs)
项目:scapy-radio    作者:BastilleResearch    | 项目源码 | 文件源码
def compressSourceAddr(self, ipv6):
        #print "compressSourceAddr"
        tmp_ip = socket.inet_pton(socket.AF_INET6, ipv6.src)

        if self.sac == 0:
            if self.sam == 0x0:
                tmp_ip = tmp_ip
            elif self.sam == 0x1:
                tmp_ip = tmp_ip[8:16]
            elif self.sam == 0x2:
                tmp_ip = tmp_ip[14:16]
            else: #self.sam == 0x3:
                pass
        else: #self.sac == 1
            if self.sam == 0x0:
                tmp_ip = "\x00"*16
            elif self.sam == 0x1:
                tmp_ip = tmp_ip[8:16]
            elif self.sam == 0x2:
                tmp_ip = tmp_ip[14:16]

        self.sourceAddr = socket.inet_ntop(socket.AF_INET6, "\x00"*(16-len(tmp_ip)) + tmp_ip)
        return self.sourceAddr
项目:flowanalyzer    作者:manitonetworks    | 项目源码 | 文件源码
def datagram_parse(
    data # type: "XDR Data"
    ):
    """Parse an sFlow high-level datagram"""
    datagram = {}
    datagram["sFlow Version"] = int(data.unpack_uint()) # sFlow Version
    datagram["IP Version"] = data.unpack_uint() # Agent IP version

    if datagram["IP Version"] == 1:
        datagram["Agent IP"] = inet_ntoa(data.unpack_fstring(4)) # sFlow Agent IP (IPv4)
    else:
        datagram["Agent IP"] = inet_ntop(data.unpack_fstring(16)) # sFlow Agent IP (IPv6)
        pass

    datagram["Sub Agent"] = data.unpack_uint() # Sub Agent ID
    datagram["Datagram Sequence Number"] = int(data.unpack_uint()) # Datagram Seq. Number
    datagram["Switch Uptime ms"] = int(data.unpack_uint()) # Switch Uptime (ms)
    datagram["Sample Count"] = int(data.unpack_uint()) # Samples in datagram
    return datagram

# HTTP Methods
项目:flowanalyzer    作者:manitonetworks    | 项目源码 | 文件源码
def parse_ipv6(
        self,
        packed_data, # type: struct
        pointer, # type: int
        field_size # type: int
        ):
        """
        Unpack an IPv6 address

        Args:
            packed_data (struct): Packed data
            pointer (int): Current unpack location
            field_size (int): Length of data to unpack

        Returns:
            str: IPv4 address
        """
        payload = self.socket.inet_ntop(self.socket.AF_INET6,packed_data[pointer:pointer+field_size])
        return payload


### Generic MAC Address Parsers ###
项目:isf    作者:w3h    | 项目源码 | 文件源码
def in6_getifaddr():
    err = create_string_buffer(PCAP_ERRBUF_SIZE)
    devs = POINTER(pcap_if_t)()
    ret = []
    if pcap_findalldevs(byref(devs), err) < 0:
      return ret
    try:
      p = devs
      ret = []
      while p:
        a = p.contents.addresses
        while a:
          if a.contents.addr.contents.sa_family == socket.AF_INET6:
            ap = a.contents.addr
            val = cast(ap, POINTER(sockaddr_in6))
            addr = socket.inet_ntop(socket.AF_INET6, str(val.contents.sin6_addr[:]))
            scope = scapy.utils6.in6_getscope(addr)
            ret.append((addr, scope, p.contents.name.decode('ascii')))
          a = a.contents.next
        p = p.contents.next
      return ret
    finally:
      pcap_freealldevs(devs)