Python socket.inet_ntop() Examples

The following are 60 code examples for showing how to use socket.inet_ntop(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 6 votes vote down vote up
def mac_set_ip_address(self, dev, ip, serverip, netmask):
		ifr = struct.pack('<16sBBHIIIBBHIIIBBHIII',
			self.iface_name,
			16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, ip))[0], 0, 0,
			16, socket.AF_INET, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, serverip))[0], 0, 0,
			16, 0, 0, struct.unpack('<L', socket.inet_pton(socket.AF_INET, "255.255.255.255"))[0], 0, 0)
		try:
			sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			fcntl.ioctl(sock, self.IOCTL_MACOSX_SIOCAIFADDR, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))
		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 2
Project: ivre   Author: cea-sec   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def bin2ip(ipval):
    """Converts a 16-bytes binary blob to an IPv4 or IPv6 standard
representation. See ip2bin().

    """
    try:
        socket.inet_aton(ipval)
        return ipval
    except (TypeError, socket.error):
        pass
    try:
        socket.inet_pton(socket.AF_INET6, ipval)
        return ipval
    except (TypeError, socket.error):
        pass
    try:
        return int2ip(ipval)
    except TypeError:
        pass
    if ipval[:12] == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff':
        return socket.inet_ntoa(ipval[12:])
    return socket.inet_ntop(socket.AF_INET6, ipval) 
Example 3
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 6 votes vote down vote up
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... 
Example 4
Project: avocado-vt   Author: avocado-framework   File: utils_net.py    License: GNU General Public License v2.0 6 votes vote down vote up
def canonicalize(self, ip_str):
        """
        Parse an IP string for listen to IPAddress content.
        """
        try:
            if ':' in ip_str:
                self.version = 'ipv6'
                if '%' in ip_str:
                    ip_str, scope = ip_str.split('%')
                    self.scope = int(scope)
                self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr)
            else:
                self.version = 'ipv4'
                self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str)
                self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr)
        except socket.error as detail:
            if 'illegal IP address' in str(detail):
                self.addr = ip_str
                self.version = 'hostname' 
Example 5
Project: BinderFilter   Author: dxwu   File: test_socket.py    License: MIT License 6 votes vote down vote up
def testStringToIPv6(self):
        if not hasattr(socket, 'inet_ntop'):
            return # No inet_ntop() on this platform
        try:
            from socket import inet_ntop, AF_INET6, has_ipv6
            if not has_ipv6:
                return
        except ImportError:
            return
        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... 
Example 6
Project: oss-ftp   Author: aliyun   File: test_socket.py    License: MIT License 6 votes vote down vote up
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... 
Example 7
Project: aiosocks   Author: nibrag   File: protocols.py    License: Apache License 2.0 6 votes vote down vote up
def read_address(self):
        atype = await self.read_response(1)

        if atype[0] == c.SOCKS5_ATYP_IPv4:
            addr = socket.inet_ntoa((await self.read_response(4)))
        elif atype[0] == c.SOCKS5_ATYP_DOMAIN:
            length = await self.read_response(1)
            addr = await self.read_response(ord(length))
        elif atype[0] == c.SOCKS5_ATYP_IPv6:
            addr = await self.read_response(16)
            addr = socket.inet_ntop(socket.AF_INET6, addr)
        else:
            raise InvalidServerReply('SOCKS5 proxy server sent invalid data')

        port = await self.read_response(2)
        port = struct.unpack('>H', port)[0]

        return addr, port 
Example 8
Project: z-ssl-proxy   Author: warriorpaw   File: z_server.py    License: Apache License 2.0 6 votes vote down vote up
def socket5proxy(self):
        try:
            sock = self.connection
            addrtype = ord(sock.recv(1))
            if addrtype > 4:
                return addrtype
            if addrtype == 1:
                addr = socket.inet_ntoa(self.rfile.read(4))
            elif addrtype == 3:
                addr = self.rfile.read(ord(sock.recv(1)))
            elif addrtype == 4:
                addr = socket.inet_ntop(socket.AF_INET6,self.rfile.read(16))
            else:
                # not support
                logging.warn('addr_type not support')
                return
            port = struct.unpack('>H', self.rfile.read(2))
            try:
                logging.info('connecting %s:%d' % (addr, port[0]))
                remote = socket.create_connection((addr, port[0]))
            except socket.error, e:
                logging.warn(e)
                return
            self.handle_socket5(sock, remote) 
Example 9
Project: flowanalyzer   Author: tyjhart   File: parser_modules.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 ### 
Example 10
Project: ja3   Author: salesforce   File: ja3.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_ip(value):
    """Convert an IP address from binary to text.

    :param value: Raw binary data to convert
    :type value: str
    :returns: str
    """
    try:
        return socket.inet_ntop(socket.AF_INET, value)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, value) 
Example 11
Project: ja3   Author: salesforce   File: ja3.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_ip(value):
    """Convert an IP address from binary to text.

    :param value: Raw binary data to convert
    :type value: str
    :returns: str
    """
    try:
        return socket.inet_ntop(socket.AF_INET, value)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, value) 
Example 12
Project: ja3   Author: salesforce   File: ja3s.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def convert_ip(value):
    """Convert an IP address from binary to text.

    :param value: Raw binary data to convert
    :type value: str
    :returns: str
    """
    try:
        return socket.inet_ntop(socket.AF_INET, value)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, value) 
Example 13
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 5 votes vote down vote up
def lin_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			# set IP
			ifr  = struct.pack('<16sH2s4s8s', dev, socket.AF_INET, "\x00"*2, socket.inet_aton(ip), "\x00"*8)
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFADDR, ifr)

			# get flags
			ifr = struct.pack('<16sh', dev, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_LINUX_IFF_UP
			ifr = struct.pack('<16sh', dev, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
		netmask = socket.inet_ntoa(integer_netmask)

		ps = subprocess.Popen(["route", "add", "-net", rangeip, "netmask", netmask, "dev", dev], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 14
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 5 votes vote down vote up
def freebsd_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			#set ip, serverip and netmask
			ifaliasreq = struct.pack('<16sBBHI8sBBHI8sBBHI8sI', self.iface_name,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(ip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(serverip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton('255.255.255.255'))[0],
				'\x00'*8,
				0)
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCAIFADDR, ifaliasreq)

			# get flags
			ifr = struct.pack('<16sh', self.iface_name, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCGIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_FREEBSD_IFF_UP
			ifr = struct.pack('<16sh', self.iface_name, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 15
Project: tcp_killer   Author: google   File: tcp_killer.py    License: Apache License 2.0 5 votes vote down vote up
def canonicalize_ip_address(address):
  if ":" in address:
    family = socket.AF_INET6
  else:
    family = socket.AF_INET
  return socket.inet_ntop(family, socket.inet_pton(family, address)) 
Example 16
Project: udger-python   Author: udger   File: base.py    License: MIT License 5 votes vote down vote up
def normalize_ipaddress(ip_string):
        try:
            packed = socket.inet_pton(socket.AF_INET, ip_string)
            ip_string = socket.inet_ntop(socket.AF_INET, packed)

            ipv6_words = None
            ipv4_int = struct.unpack("!L", packed)[0]
        except socket.error:
            packed = socket.inet_pton(socket.AF_INET6, ip_string)
            ip_string = socket.inet_ntop(socket.AF_INET6, packed)

            ipv6_words = struct.unpack("!8H", packed)
            ipv4_int = None

        return ip_string, ipv4_int, ipv6_words 
Example 17
Project: checklocktimeverify-demos   Author: petertodd   File: net.py    License: GNU General Public License v3.0 5 votes vote down vote up
def stream_deserialize(cls, f, without_time=False):
        c = cls()
        if c.protover >= CADDR_TIME_VERSION and not without_time:
            c.nTime = struct.unpack(b"<I", ser_read(f, 4))[0]
        c.nServices = struct.unpack(b"<Q", ser_read(f, 8))[0]
        
        packedIP = ser_read(f, 16)

        if bytes(packedIP[0:12]) == IPV4_COMPAT: # IPv4 
            c.ip = socket.inet_ntop(socket.AF_INET, packedIP[12:16])
        else: #IPv6
            c.ip = socket.inet_ntop(socket.AF_INET6, packedIP)

        c.port = struct.unpack(b">H", ser_read(f, 2))[0]
        return c 
Example 18
Project: checklocktimeverify-demos   Author: petertodd   File: net.py    License: GNU General Public License v3.0 5 votes vote down vote up
def stream_deserialize(cls, f, without_time=False):
        c = cls()
        if c.protover >= CADDR_TIME_VERSION and not without_time:
            c.nTime = struct.unpack(b"<I", ser_read(f, 4))[0]
        c.nServices = struct.unpack(b"<Q", ser_read(f, 8))[0]
        
        packedIP = ser_read(f, 16)

        if bytes(packedIP[0:12]) == IPV4_COMPAT: # IPv4 
            c.ip = socket.inet_ntop(socket.AF_INET, packedIP[12:16])
        else: #IPv6
            c.ip = socket.inet_ntop(socket.AF_INET6, packedIP)

        c.port = struct.unpack(b">H", ser_read(f, 2))[0]
        return c 
Example 19
Project: neverendshadowsocks   Author: ntfreedom   File: asyncdns.py    License: Apache License 2.0 5 votes vote down vote up
def parse_ip(addrtype, data, length, offset):
    if addrtype == QTYPE_A:
        return socket.inet_ntop(socket.AF_INET, data[offset:offset + length])
    elif addrtype == QTYPE_AAAA:
        return socket.inet_ntop(socket.AF_INET6, data[offset:offset + length])
    elif addrtype in [QTYPE_CNAME, QTYPE_NS]:
        return parse_name(data, offset)[1]
    else:
        return data[offset:offset + length] 
Example 20
Project: neverendshadowsocks   Author: ntfreedom   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def inet_ntop(family, ipstr):
    if family == socket.AF_INET:
        return to_bytes(socket.inet_ntoa(ipstr))
    elif family == socket.AF_INET6:
        import re
        v6addr = ':'.join(('%02X%02X' % (ord(i), ord(j))).lstrip('0')
                          for i, j in zip(ipstr[::2], ipstr[1::2]))
        v6addr = re.sub('::+', '::', v6addr, count=1)
        return to_bytes(v6addr) 
Example 21
Project: neverendshadowsocks   Author: ntfreedom   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def patch_socket():
    if not hasattr(socket, 'inet_pton'):
        socket.inet_pton = inet_pton

    if not hasattr(socket, 'inet_ntop'):
        socket.inet_ntop = inet_ntop 
Example 22
Project: neverendshadowsocks   Author: ntfreedom   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def parse_header(data):
    addrtype = ord(data[0])
    dest_addr = None
    dest_port = None
    header_length = 0
    if addrtype == ADDRTYPE_IPV4:
        if len(data) >= 7:
            dest_addr = socket.inet_ntoa(data[1:5])
            dest_port = struct.unpack('>H', data[5:7])[0]
            header_length = 7
        else:
            logging.warn('header is too short')
    elif addrtype == ADDRTYPE_HOST:
        if len(data) > 2:
            addrlen = ord(data[1])
            if len(data) >= 2 + addrlen:
                dest_addr = data[2:2 + addrlen]
                dest_port = struct.unpack('>H', data[2 + addrlen:4 +
                                                     addrlen])[0]
                header_length = 4 + addrlen
            else:
                logging.warn('header is too short')
        else:
            logging.warn('header is too short')
    elif addrtype == ADDRTYPE_IPV6:
        if len(data) >= 19:
            dest_addr = socket.inet_ntop(socket.AF_INET6, data[1:17])
            dest_port = struct.unpack('>H', data[17:19])[0]
            header_length = 19
        else:
            logging.warn('header is too short')
    else:
        logging.warn('unsupported addrtype %d, maybe wrong password or '
                     'encryption method' % addrtype)
    if dest_addr is None:
        return None
    return addrtype, to_bytes(dest_addr), dest_port, header_length 
Example 23
Project: neverendshadowsocks   Author: ntfreedom   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def test_inet_conv():
    ipv4 = b'8.8.4.4'
    b = inet_pton(socket.AF_INET, ipv4)
    assert inet_ntop(socket.AF_INET, b) == ipv4
    ipv6 = b'2404:6800:4005:805::1011'
    b = inet_pton(socket.AF_INET6, ipv6)
    assert inet_ntop(socket.AF_INET6, b) == ipv6 
Example 24
Project: rekall   Author: google   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def my_chr(value):
    if isinstance(value, str):
        return value

    return chr(value)


# Compensate for Windows python not supporting socket.inet_ntop and some
# Linux systems (i.e. OpenSuSE 11.2 w/ Python 2.6) not supporting IPv6. 
Example 25
Project: rekall   Author: google   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def FormatIPAddress(family, value):
    """Formats a value as an ascii IP address determined by family."""
    if value == None:
        return value

    return socket.inet_ntop(
        getattr(socket, str(family)),
        value.obj_vm.read(value.obj_offset, value.obj_size)) 
Example 26
Project: ivre   Author: cea-sec   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def int2ip(ipint):
    """Converts the integer representation of an IP address to its
    classical decimal, dot-separated (for IPv4) or hexadecimal,
    colon-separated (for IPv6) string representation.

    """
    try:
        return socket.inet_ntoa(struct.pack('!I', ipint))
    except struct.error:
        return socket.inet_ntop(
            socket.AF_INET6,
            struct.pack('!QQ', ipint >> 64, ipint & 0xffffffffffffffff),
        ) 
Example 27
Project: ivre   Author: cea-sec   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def int2ip6(ipint):
    """Converts the integer representation of an IPv6 address to its
    classical decimal, hexadecimal, colon-separated string
    representation.

    """
    return socket.inet_ntop(
        socket.AF_INET6,
        struct.pack('!QQ', ipint >> 64, ipint & 0xffffffffffffffff),
    ) 
Example 28
Project: CloudFail   Author: m0rtem   File: socks.py    License: MIT License 5 votes vote down vote up
def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy
        family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}

        # If the given destination address is an IP address, we'll
        # use the IP address request even if remote resolving was specified.
        # Detect whether the address is IPv4/6 directly.
        for family in (socket.AF_INET, socket.AF_INET6):
            try:
                addr_bytes = socket.inet_pton(family, host)
                file.write(family_to_byte[family] + addr_bytes)
                host = socket.inet_ntop(family, addr_bytes)
                file.write(struct.pack(">H", port))
                return host, port
            except socket.error:
                continue

        # Well it's not an IP number, so it's probably a DNS name.
        if rdns:
            # Resolve remotely
            host_bytes = host.encode('idna')
            file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
        else:
            # Resolve locally
            addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
            # We can't really work out what IP is reachable, so just pick the
            # first.
            target_addr = addresses[0]
            family = target_addr[0]
            host = target_addr[4][0]

            addr_bytes = socket.inet_pton(family, host)
            file.write(family_to_byte[family] + addr_bytes)
            host = socket.inet_ntop(family, addr_bytes)
        file.write(struct.pack(">H", port))
        return host, port 
Example 29
Project: CloudFail   Author: m0rtem   File: socks.py    License: MIT License 5 votes vote down vote up
def _read_SOCKS5_address(self, file):
        atyp = self._readall(file, 1)
        if atyp == b"\x01":
            addr = socket.inet_ntoa(self._readall(file, 4))
        elif atyp == b"\x03":
            length = self._readall(file, 1)
            addr = self._readall(file, ord(length))
        elif atyp == b"\x04":
            addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        port = struct.unpack(">H", self._readall(file, 2))[0]
        return addr, port 
Example 30
Project: ironpython2   Author: IronLanguages   File: test_socket.py    License: Apache License 2.0 5 votes vote down vote up
def testStringToIPv4(self):
        from socket import inet_ntoa as f, inet_ntop, AF_INET
        g = lambda a: inet_ntop(AF_INET, a)

        self.assertEqual('1.0.1.0', f('\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', f('\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', f('\xff\xff\xff\xff'))
        self.assertEqual('1.2.3.4', f('\x01\x02\x03\x04'))

        self.assertEqual('1.0.1.0', g('\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', g('\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', g('\xff\xff\xff\xff')) 
Example 31
Project: aumfor   Author: virtualrealitysystems   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def remove_unprintable(str):
    return ''.join([c for c in str if (ord(c) > 31 or ord(c) == 9) and ord(c) <= 126])

# Compensate for Windows python not supporting socket.inet_ntop and some
# Linux systems (i.e. OpenSuSE 11.2 w/ Python 2.6) not supporting IPv6. 
Example 32
Project: selenium-wire   Author: wkeeling   File: socks.py    License: MIT License 5 votes vote down vote up
def _read_SOCKS5_address(self, file):
        atyp = self._readall(file, 1)
        if atyp == b"\x01":
            addr = socket.inet_ntoa(self._readall(file, 4))
        elif atyp == b"\x03":
            length = self._readall(file, 1)
            addr = self._readall(file, ord(length))
        elif atyp == b"\x04":
            addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        port = struct.unpack(">H", self._readall(file, 2))[0]
        return addr, port 
Example 33
Project: faces   Author: skarlekar   File: socks.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy
        family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}

        # If the given destination address is an IP address, we'll
        # use the IP address request even if remote resolving was specified.
        # Detect whether the address is IPv4/6 directly.
        for family in (socket.AF_INET, socket.AF_INET6):
            try:
                addr_bytes = socket.inet_pton(family, host)
                file.write(family_to_byte[family] + addr_bytes)
                host = socket.inet_ntop(family, addr_bytes)
                file.write(struct.pack(">H", port))
                return host, port
            except socket.error:
                continue

        # Well it's not an IP number, so it's probably a DNS name.
        if rdns:
            # Resolve remotely
            host_bytes = host.encode('idna')
            file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
        else:
            # Resolve locally
            addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
            # We can't really work out what IP is reachable, so just pick the
            # first.
            target_addr = addresses[0]
            family = target_addr[0]
            host = target_addr[4][0]

            addr_bytes = socket.inet_pton(family, host)
            file.write(family_to_byte[family] + addr_bytes)
            host = socket.inet_ntop(family, addr_bytes)
        file.write(struct.pack(">H", port))
        return host, port 
Example 34
Project: faces   Author: skarlekar   File: socks.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _read_SOCKS5_address(self, file):
        atyp = self._readall(file, 1)
        if atyp == b"\x01":
            addr = socket.inet_ntoa(self._readall(file, 4))
        elif atyp == b"\x03":
            length = self._readall(file, 1)
            addr = self._readall(file, ord(length))
        elif atyp == b"\x04":
            addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        port = struct.unpack(">H", self._readall(file, 2))[0]
        return addr, port 
Example 35
Project: phpsploit   Author: nil0x42   File: socks.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy
        family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}

        # If the given destination address is an IP address, we'll
        # use the IP address request even if remote resolving was specified.
        # Detect whether the address is IPv4/6 directly.
        for family in (socket.AF_INET, socket.AF_INET6):
            try:
                addr_bytes = socket.inet_pton(family, host)
                file.write(family_to_byte[family] + addr_bytes)
                host = socket.inet_ntop(family, addr_bytes)
                file.write(struct.pack(">H", port))
                return host, port
            except socket.error:
                continue

        # Well it's not an IP number, so it's probably a DNS name.
        if rdns:
            # Resolve remotely
            host_bytes = host.encode('idna')
            file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
        else:
            # Resolve locally
            addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
            # We can't really work out what IP is reachable, so just pick the
            # first.
            target_addr = addresses[0]
            family = target_addr[0]
            host = target_addr[4][0]

            addr_bytes = socket.inet_pton(family, host)
            file.write(family_to_byte[family] + addr_bytes)
            host = socket.inet_ntop(family, addr_bytes)
        file.write(struct.pack(">H", port))
        return host, port 
Example 36
Project: phpsploit   Author: nil0x42   File: socks.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _read_SOCKS5_address(self, file):
        atyp = self._readall(file, 1)
        if atyp == b"\x01":
            addr = socket.inet_ntoa(self._readall(file, 4))
        elif atyp == b"\x03":
            length = self._readall(file, 1)
            addr = self._readall(file, ord(length))
        elif atyp == b"\x04":
            addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        port = struct.unpack(">H", self._readall(file, 2))[0]
        return addr, port 
Example 37
Project: nightmare   Author: joxeankoret   File: dns.py    License: GNU General Public License v2.0 5 votes vote down vote up
def getDnsAnswers(self):
        ret = []
        for fname, a in self.records.answers.vsGetFields():

            adata = a.qdata
            if a.qtype == DNS_TYPE_A:
                adata = socket.inet_ntop(socket.AF_INET, adata)

            ret.append( (a.qtype, a.qclass, a.qttl, a.qname.getFullName(self), adata) )

        return ret 
Example 38
Project: nightmare   Author: joxeankoret   File: inet.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self):
        bytes = struct.pack('>I', self._vs_value)
        return socket.inet_ntop(socket.AF_INET, bytes) 
Example 39
Project: BinderFilter   Author: dxwu   File: test_socket.py    License: MIT License 5 votes vote down vote up
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)

        self.assertEqual('1.0.1.0', f('\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', f('\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', f('\xff\xff\xff\xff'))
        self.assertEqual('1.2.3.4', f('\x01\x02\x03\x04'))

        self.assertEqual('1.0.1.0', g('\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', g('\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', g('\xff\xff\xff\xff')) 
Example 40
Project: oss-ftp   Author: aliyun   File: test_socket.py    License: MIT License 5 votes vote down vote up
def testStringToIPv4(self):
        from socket import inet_ntoa as f, inet_ntop, AF_INET
        g = lambda a: inet_ntop(AF_INET, a)

        self.assertEqual('1.0.1.0', f('\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', f('\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', f('\xff\xff\xff\xff'))
        self.assertEqual('1.2.3.4', f('\x01\x02\x03\x04'))

        self.assertEqual('1.0.1.0', g('\x01\x00\x01\x00'))
        self.assertEqual('170.85.170.85', g('\xaa\x55\xaa\x55'))
        self.assertEqual('255.255.255.255', g('\xff\xff\xff\xff')) 
Example 41
Project: aiosocks   Author: nibrag   File: protocols.py    License: Apache License 2.0 5 votes vote down vote up
def build_dst_address(self, host, port):
        family_to_byte = {socket.AF_INET: c.SOCKS5_ATYP_IPv4,
                          socket.AF_INET6: c.SOCKS5_ATYP_IPv6}
        port_bytes = struct.pack('>H', port)

        # if the given destination address is an IP address, we will
        # use the IP address request even if remote resolving was specified.
        for family in (socket.AF_INET, socket.AF_INET6):
            try:
                host_bytes = socket.inet_pton(family, host)
                req = [family_to_byte[family], host_bytes, port_bytes]
                return req, (host, port)
            except socket.error:
                pass

        # it's not an IP number, so it's probably a DNS name.
        if self._remote_resolve:
            host_bytes = host.encode('idna')
            req = [c.SOCKS5_ATYP_DOMAIN, chr(len(host_bytes)).encode(),
                   host_bytes, port_bytes]
        else:
            family, host_bytes = await self._get_dst_addr()
            host_bytes = socket.inet_pton(family, host_bytes)
            req = [family_to_byte[family], host_bytes, port_bytes]
            host = socket.inet_ntop(family, host_bytes)

        return req, (host, port) 
Example 42
Project: async_dns   Author: gera2ld   File: record.py    License: MIT License 5 votes vote down vote up
def parse(self, data, l):
        l, self.name = utils.load_message(data, l)
        self.qtype, self.qclass = struct.unpack('!HH', data[l: l + 4])
        l += 4
        if self.q == RESPONSE:
            self.timestamp = int(time.time())
            self.ttl, dl = struct.unpack('!LH', data[l: l + 6])
            l += 6
            if self.qtype == types.A:
                self.data = socket.inet_ntoa(data[l: l + dl])
            elif self.qtype == types.AAAA:
                self.data = socket.inet_ntop(socket.AF_INET6, data[l: l + dl])
            elif self.qtype == types.MX:
                _, self.data = MX_RData.load(data, l)
            elif self.qtype == types.SRV:
                _, self.data = SRV_RData.load(data, l)
            elif self.qtype == types.NAPTR:
                _, self.data = NAPTR_RData.load(data, l)
            elif self.qtype == types.SOA:
                _, self.data = SOA_RData.load(data, l)
            elif self.qtype in (types.CNAME, types.NS, types.PTR, types.TXT):
                _, self.data = utils.load_message(data, l)
            else:
                self.data = data[l: l + dl]
            l += dl
        return l 
Example 43
Project: pynng   Author: codypiersall   File: sockaddr.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        as_bytes = struct.pack('I', self.addr)
        ip = socket.inet_ntop(socket.AF_INET, as_bytes)
        port = socket.ntohs(self.port)
        return '{}:{}'.format(ip, port) 
Example 44
Project: pynng   Author: codypiersall   File: sockaddr.py    License: MIT License 5 votes vote down vote up
def __str__(self):
        # TODO: not a good string repr at all
        ip = socket.inet_ntop(socket.AF_INET6, self.addr)
        port = socket.ntohs(self.port)
        return "[{}]:{}".format(ip, port) 
Example 45
Project: z-ssl-proxy   Author: warriorpaw   File: z_server.py    License: Apache License 2.0 5 votes vote down vote up
def tcpproxy(self, addrtype):
        self.tcpruning = True
        try:
            sock = self.connection
            if addrtype == 8:
                self.remote = TCP_CLIENTS.handleproxy(self)
                if self.remote:
                    self.handle_TCP()
                return
            elif addrtype == 5:
                addr = socket.inet_ntoa(self.rfile.read(4))
            elif addrtype == 6:
                addr = self.rfile.read(ord(sock.recv(1)))
            elif addrtype == 7:
                addr = socket.inet_ntop(socket.AF_INET6,self.rfile.read(16))
            else:
                # not support
                logging.warn('addr_type not support')
                return
            port = struct.unpack('>H', self.rfile.read(2))
            clientID = hashlib.sha1(str(self.client_address) + random_data(20) + str(time.time())).digest()
            self.remote = TCP_CLIENTS.newproxy(clientID, addr, port[0], self)
            if self.remote:
                self.handle_TCP()
            return
        except socket.error, e:
            logging.warn(e)
            return 
Example 46
Project: Google-Alfred3-Workflow   Author: ethan-funny   File: socks.py    License: MIT License 5 votes vote down vote up
def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy
        family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"}

        # If the given destination address is an IP address, we'll
        # use the IP address request even if remote resolving was specified.
        # Detect whether the address is IPv4/6 directly.
        for family in (socket.AF_INET, socket.AF_INET6):
            try:
                addr_bytes = socket.inet_pton(family, host)
                file.write(family_to_byte[family] + addr_bytes)
                host = socket.inet_ntop(family, addr_bytes)
                file.write(struct.pack(">H", port))
                return host, port
            except socket.error:
                continue

        # Well it's not an IP number, so it's probably a DNS name.
        if rdns:
            # Resolve remotely
            host_bytes = host.encode('idna')
            file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
        else:
            # Resolve locally
            addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)
            # We can't really work out what IP is reachable, so just pick the
            # first.
            target_addr = addresses[0]
            family = target_addr[0]
            host = target_addr[4][0]

            addr_bytes = socket.inet_pton(family, host)
            file.write(family_to_byte[family] + addr_bytes)
            host = socket.inet_ntop(family, addr_bytes)
        file.write(struct.pack(">H", port))
        return host, port 
Example 47
Project: Google-Alfred3-Workflow   Author: ethan-funny   File: socks.py    License: MIT License 5 votes vote down vote up
def _read_SOCKS5_address(self, file):
        atyp = self._readall(file, 1)
        if atyp == b"\x01":
            addr = socket.inet_ntoa(self._readall(file, 4))
        elif atyp == b"\x03":
            length = self._readall(file, 1)
            addr = self._readall(file, ord(length))
        elif atyp == b"\x04":
            addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        port = struct.unpack(">H", self._readall(file, 2))[0]
        return addr, port 
Example 48
Project: abusehelper   Author: abusesa   File: vxvaultbot.py    License: MIT License 5 votes vote down vote up
def i_am_a_name(string):
    for addr_type in (socket.AF_INET, socket.AF_INET6):
        try:
            socket.inet_ntop(addr_type, socket.inet_pton(addr_type, string))
        except (ValueError, socket.error):
            pass
        else:
            return False
    return True 
Example 49
Project: abusehelper   Author: abusesa   File: updates.py    License: MIT License 5 votes vote down vote up
def parse_ip(value):
    for addr_type in (socket.AF_INET, socket.AF_INET6):
        try:
            return socket.inet_ntop(addr_type, socket.inet_pton(addr_type, value))
        except (ValueError, socket.error):
            pass
    return None 
Example 50
Project: abusehelper   Author: abusesa   File: phishtankbot.py    License: MIT License 5 votes vote down vote up
def is_domain(string):
    for addr_type in (socket.AF_INET, socket.AF_INET6):
        try:
            socket.inet_ntop(addr_type, socket.inet_pton(addr_type, string))
        except (ValueError, socket.error):
            pass
        else:
            return False
    return True 
Example 51
Project: abusehelper   Author: abusesa   File: __init__.py    License: MIT License 5 votes vote down vote up
def parse_ip(string):
    for addr_type in (socket.AF_INET, socket.AF_INET6):
        try:
            return socket.inet_ntop(addr_type, socket.inet_pton(addr_type, string))
        except (ValueError, socket.error):
            pass
    return None 
Example 52
Project: abusehelper   Author: abusesa   File: cymruwhois.py    License: MIT License 5 votes vote down vote up
def _parse_ip(string, families=(socket.AF_INET, socket.AF_INET6)):
    for family in families:
        try:
            return socket.inet_ntop(family, socket.inet_pton(family, string))
        except (ValueError, socket.error):
            pass
    return None 
Example 53
Project: abusehelper   Author: abusesa   File: iprange.py    License: MIT License 5 votes vote down vote up
def format_ipv6(ip_num):
    hi = ip_num >> 64
    lo = ip_num & 0xffffffffffffffff
    return inet_ntop(AF_INET6, struct.pack("!QQ", hi, lo)) 
Example 54
Project: Safejumper-for-Desktop   Author: proxysh   File: compat.py    License: GNU General Public License v2.0 5 votes vote down vote up
def inet_ntop(af, addr):
    if af == socket.AF_INET:
        return socket.inet_ntoa(addr)
    elif af == socket.AF_INET6:
        if len(addr) != 16:
            raise ValueError("address length incorrect")
        parts = struct.unpack('!8H', addr)
        curBase = bestBase = None
        for i in range(8):
            if not parts[i]:
                if curBase is None:
                    curBase = i
                    curLen = 0
                curLen += 1
            else:
                if curBase is not None:
                    bestLen = None
                    if bestBase is None or curLen > bestLen:
                        bestBase = curBase
                        bestLen = curLen
                    curBase = None
        if curBase is not None and (bestBase is None or curLen > bestLen):
            bestBase = curBase
            bestLen = curLen
        parts = [hex(x)[2:] for x in parts]
        if bestBase is not None:
            parts[bestBase:bestBase + bestLen] = ['']
        if parts[0] == '':
            parts.insert(0, '')
        if parts[-1] == '':
            parts.insert(len(parts) - 1, '')
        return ':'.join(parts)
    else:
        raise socket.error(97, 'Address family not supported by protocol') 
Example 55
Project: Safejumper-for-Desktop   Author: proxysh   File: dns.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        return '<A6 %s %s (%d) ttl=%s>' % (
            self.prefix,
            socket.inet_ntop(AF_INET6, self.suffix),
            self.prefixLen, self.ttl
        ) 
Example 56
Project: Safejumper-for-Desktop   Author: proxysh   File: common.py    License: GNU General Public License v2.0 5 votes vote down vote up
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)) 
Example 57
Project: website-fingerprinting   Author: wisepythagoras   File: utils.py    License: MIT License 5 votes vote down vote up
def inet_to_str(inet):
    """ Convert inet object to a string """

    return socket.inet_ntop(socket.AF_INET, inet) 
Example 58
Project: plex-for-kodi   Author: plexinc   File: getifaddrs.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        try:
            assert self.sin_len >= sizeof(sockaddr_in)
            data = ''.join(map(chr, self.sin_addr))
            return socket.inet_ntop(socket.AF_INET, data)
        except:
            return '' 
Example 59
Project: plex-for-kodi   Author: plexinc   File: getifaddrs.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        try:
            assert self.sin6_len >= sizeof(sockaddr_in6)
            data = ''.join(map(chr, self.sin6_addr))
            return socket.inet_ntop(socket.AF_INET6, data)
        except:
            return '' 
Example 60
Project: wstan   Author: krrr   File: __init__.py    License: MIT License 5 votes vote down vote up
def parse_socks_addr(dat, allow_remain=False):
    """Extract address and port from SOCKS request header (only 4 parts:
    RSV(0x00) | ATYP | DST.ADDR | DST.PORT). The header will be reused in tunnel server."""
    if not dat or dat[0] != 0x00:
        raise ValueError
    try:
        atyp = dat[1]
        if atyp == 0x01:  # IPv4
            port_idx = 6
            target_addr = socket.inet_ntoa(dat[2:port_idx])
        elif atyp == 0x03:  # domain name
            port_idx = 3 + dat[2]
            target_addr = dat[3:port_idx].decode('ascii')
        elif atyp == 0x04:  # IPv6
            port_idx = 18
            target_addr = socket.inet_ntop(socket.AF_INET6, dat[2:port_idx])
        else:
            raise ValueError
        target_port = struct.unpack('>H', dat[port_idx:port_idx+2])[0]
        if allow_remain:
            return target_addr, target_port, port_idx + 2
        else:
            if dat[port_idx+2:]:
                raise ValueError
            return target_addr, target_port
    except (IndexError, struct.error):
        raise ValueError