Python socket.inet_ntoa() Examples

The following are 30 code examples of socket.inet_ntoa(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: ip.py    From pynmap with GNU General Public License v3.0 8 votes vote down vote up
def getLocalip(interface: str = "wlan0") -> str:
    """This function will return the Local IP Address of the interface"""
    if "nux" in sys.platform:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            return socket.inet_ntoa(
                fcntl.ioctl(
                    s.fileno(), 0x8915, struct.pack('256s',interface[:15])
                )[20:24]
            )
        except IOError:
            print("{}[!] Error, unable to detect local ip address.".format(Colors.FAIL))
            print("[!] Check your connection to network {}".format(Colors.ENDC))
            exit()
    elif "darwin" in sys.platform:
        return [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0] 
Example #2
Source File: utils.py    From optitrack with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_ip_address(ifname):
  """
  Get the ip address from the specified interface.
    
    >>> get_ip_address('eth0')
    '192.168.0.7'
    
  @type ifname: string
  @param ifname: The interface name. Typical names are C{'eth0'}, 
  C{'wlan0'}, etc.
  @rtype: string
  @return: The IP address of the specified interface.
  """
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  return socket.inet_ntoa(fcntl.ioctl(
      s.fileno(),
      0x8915,  # SIOCGIFADDR
      struct.pack('256s', ifname[:15]))[20:24]) 
Example #3
Source File: gateway.py    From Jtyoui with MIT License 6 votes vote down vote up
def get_linux_ip(eth):
    """在Linux下获取IP"""
    assert os.name == 'posix', NotLinuxSystemError('不是Linux系统')
    import fcntl
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth[:15])))
    return ip[20:24] 
Example #4
Source File: Sniffer.py    From SimpleSniffer with GNU General Public License v3.0 6 votes vote down vote up
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])

#嗅探 
Example #5
Source File: utils.py    From ivre with 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 #6
Source File: multicast-relay.py    From multicast-relay with GNU General Public License v3.0 6 votes vote down vote up
def interfaces(self):
        if self.homebrewNetifaces:
            import array
            import fcntl

            maxInterfaces = 128
            bufsiz = maxInterfaces * 40
            nullByte = b'\0'

            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            ifNames = array.array('B', nullByte * bufsiz)
            ifNameLen = struct.unpack('iL', fcntl.ioctl(
                s.fileno(),
                0x8912, # SIOCGIFCONF
                struct.pack('iL', bufsiz, ifNames.buffer_info()[0])
            ))[0]

            if ifNameLen % self.ifNameStructLen != 0:
                print('Do you need to set --ifNameStructLen? %s/%s ought to have a remainder of zero.' % (ifNameLen, self.ifNameStructLen))
                sys.exit(1)

            ifNames = ifNames.tostring()
            for i in range(0, ifNameLen, self.ifNameStructLen):
                name      = ifNames[i:i+16].split(nullByte, 1)[0].decode()
                if not name:
                    print('Cannot determine interface name: do you need to set --ifNameStructLen? %s/%s ought to have a remainder of zero.' % (ifNameLen, self.ifNameStructLen))
                    sys.exit(1)
                ip        = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8915, struct.pack('256s', str(name)))[20:24]) # SIOCGIFADDR
                netmask   = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x891b, struct.pack('256s', str(name)))[20:24]) # SIOCGIFNETMASK
                broadcast = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8919, struct.pack('256s', str(name)))[20:24]) # SIOCGIFBRDADDR
                hwaddr    = ':'.join(['%02x' % ord(char) for char in fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 0x8927, struct.pack('256s', str(name)))[18:24]]) # SIOCGIFHWADDR
                self.interfaceAttrs[name] = {Netifaces.AF_LINK: [{'addr': hwaddr}], Netifaces.AF_INET: [{'addr': ip, 'netmask': netmask, 'broadcast': broadcast}]}
            return self.interfaceAttrs.keys()
        else:
            import netifaces
            return netifaces.interfaces() 
Example #7
Source File: network.py    From stem with GNU Lesser General Public License v3.0 6 votes vote down vote up
def negotiate_socks(sock, host, port):
  """
  Negotiate with a socks4a server. Closes the socket and raises an exception on
  failure.

  :param socket sock: socket connected to socks4a server
  :param str host: hostname/IP to connect to
  :param int port: port to connect to

  :raises: :class:`stem.ProtocolError` if the socks server doesn't grant our request

  :returns: a list with the IP address and the port that the proxy connected to
  """

  # SOCKS4a request here - http://en.wikipedia.org/wiki/SOCKS#Protocol
  request = b'\x04\x01' + struct.pack('!H', port) + b'\x00\x00\x00\x01' + b'\x00' + stem.util.str_tools._to_bytes(host) + b'\x00'
  sock.sendall(request)
  response = sock.recv(8)

  if len(response) != 8 or response[0:2] != b'\x00\x5a':
    sock.close()
    raise stem.ProtocolError(ERROR_MSG.get(response[1], 'SOCKS server returned unrecognized error code'))

  return [socket.inet_ntoa(response[4:]), struct.unpack('!H', response[2:4])[0]] 
Example #8
Source File: rpc_client.py    From dgl with Apache License 2.0 6 votes vote down vote up
def local_ip4_addr_list():
    """Return a set of IPv4 address
    """
    assert os.name != 'nt', 'Do not support Windows rpc yet.'
    nic = set()
    for if_nidx in socket.if_nameindex():
        name = if_nidx[1]
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            ip_of_ni = fcntl.ioctl(sock.fileno(),
                                   0x8915,  # SIOCGIFADDR
                                   struct.pack('256s', name[:15].encode("UTF-8")))
        except OSError as e:
            if e.errno == 99: # EADDRNOTAVAIL
                print("Warning!",
                      "Interface: {}".format(name),
                      "IP address not available for interface.",
                      sep='\n')
                continue
            else:
                raise e

        ip_addr = socket.inet_ntoa(ip_of_ni[20:24])
        nic.add(ip_addr)
    return nic 
Example #9
Source File: makeNetwork.py    From firmanal with MIT License 6 votes vote down vote up
def findNonLoInterfaces(data, endianness):
    lines = stripTimestamps(data)
    candidates = filter(lambda l: l.startswith("__inet_insert_ifa"), lines) # logs for the inconfig process
    if debug:
        print("Candidate ifaces: %r" % candidates)
    result = []
    if endianness == "eb":
        fmt = ">I"
    elif endianness == "el":
        fmt = "<I"
    for c in candidates:
        g = re.match(r"^__inet_insert_ifa\[[^\]]+\]: device:([^ ]+) ifa:0x([0-9a-f]+)", c)
        if g:
            (iface, addr) = g.groups()
            addr = socket.inet_ntoa(struct.pack(fmt, int(addr, 16)))
            if addr != "127.0.0.1" and addr != "0.0.0.0":
                result.append((iface, addr))
    return result 
Example #10
Source File: interface.py    From XFLTReaT with MIT License 6 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 #11
Source File: addresses.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def maxIpaddr(ipaddr, netmask):
    """
        Takes a quad dot format IP address string and makes it the largest valid value still in the same subnet.

        Returns:
            Max quad dot IP string or None if error
    """
    try:
        val = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
        nm = struct.unpack("!I", socket.inet_aton(netmask))[0]
        inc = struct.unpack("!I", socket.inet_aton("0.0.0.254"))[0]
        val &= nm
        val |= inc
        return socket.inet_ntoa(struct.pack('!I', val))
    except Exception:
        return None 
Example #12
Source File: hostdetails.py    From pythonpentest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_ip(inter):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip_addr = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', inter[:15]))[20:24])
    return ip_addr 
Example #13
Source File: utils_net.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def get_ip(self):
        """
        Get ip address of this interface
        """
        ifreq = struct.pack('16sH14s', self.name.encode(),
                            socket.AF_INET, b'\x00' * 14)
        try:
            res = fcntl.ioctl(sockfd, arch.SIOCGIFADDR, ifreq)
        except IOError:
            return None
        ip = struct.unpack('16sH2x4s8x', res)[2]

        return socket.inet_ntoa(ip) 
Example #14
Source File: util.py    From pyvpn with The Unlicense 5 votes vote down vote up
def inet_ltoa(addr_long):
    '''
    @summary: 转换 整数 到字符串的IP地址
    :param addr_long: 整数地址,可以直接被ping的地址
    '''
    return socket.inet_ntoa(struct.pack('!I', addr_long)) 
Example #15
Source File: utils.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def dotted_netmask(mask):
    """
    Converts mask from /xx format to xxx.xxx.xxx.xxx
    Example: if mask is 24 function returns 255.255.255.0
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example #16
Source File: utils.py    From pledgeservice with Apache License 2.0 5 votes vote down vote up
def dotted_netmask(mask):
    """
    Converts mask from /xx format to xxx.xxx.xxx.xxx
    Example: if mask is 24 function returns 255.255.255.0
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example #17
Source File: kvclient.py    From dgl with Apache License 2.0 5 votes vote down vote up
def local_ip4_addr_list():
    """Return a set of IPv4 address
    """
    nic = set()

    for ix in socket.if_nameindex():
        name = ix[1]
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ip = socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', name[:15].encode("UTF-8")))[20:24])
        nic.add(ip)

    return nic 
Example #18
Source File: socks.py    From CloudFail with 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 #19
Source File: cdp.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def get_ip_address(self, offset = 0, ip = None):
        if not ip:
            ip = self.get_bytes().tostring()[offset : offset + IP_ADDRESS_LENGTH]
        return socket.inet_ntoa( ip ) 
Example #20
Source File: NetUtils.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def num_to_dotted_quad(addr):
    "convert long int to dotted quad string"
    return socket.inet_ntoa(struct.pack('!L', addr)) 
Example #21
Source File: DeprecatedNetworks.py    From pcocc with GNU General Public License v3.0 5 votes vote down vote up
def num_to_dotted_quad(addr):
    "convert long int to dotted quad string"
    return socket.inet_ntoa(struct.pack('!L', addr)) 
Example #22
Source File: ber.py    From dionaea with GNU General Public License v2.0 5 votes vote down vote up
def do_dec(cls, s, context=None, safe=False):
        l,s,t = cls.check_type_check_len(s)
        try:
            ipaddr_ascii = inet_ntoa(s)
        except Exception:
            raise BER_Decoding_Error(
                "IP address could not be decoded", decoded=obj)
        return cls.asn1_object(ipaddr_ascii), t 
Example #23
Source File: utils.py    From NEIE-Assistant with GNU General Public License v3.0 5 votes vote down vote up
def dotted_netmask(mask):
    """Converts mask from /xx format to xxx.xxx.xxx.xxx

    Example: if mask is 24 function returns 255.255.255.0

    :rtype: str
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example #24
Source File: server.py    From SniffVPN with GNU General Public License v3.0 5 votes vote down vote up
def get_ip_address(ifname):
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  return socket.inet_ntoa(fcntl.ioctl(s.fileno(),
    0x8915,  # SIOCGIFADDR
    struct.pack('256s', ifname[:15]))[20:24]) 
Example #25
Source File: utils.py    From jbox with MIT License 5 votes vote down vote up
def dotted_netmask(mask):
    """
    Converts mask from /xx format to xxx.xxx.xxx.xxx
    Example: if mask is 24 function returns 255.255.255.0
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example #26
Source File: basic.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def v(self, vm=None):
        value = super(Ipv4Address, self).v(vm=vm)
        return socket.inet_ntoa(struct.pack("<I", value)) 
Example #27
Source File: utils.py    From jbox with MIT License 5 votes vote down vote up
def dotted_netmask(mask):
    """
    Converts mask from /xx format to xxx.xxx.xxx.xxx
    Example: if mask is 24 function returns 255.255.255.0
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example #28
Source File: bamf.py    From bamf with GNU General Public License v3.0 5 votes vote down vote up
def cidr_to_ip_range(cidr):
    ip, _, cidr = str(cidr).partition('/')
    if not (valid_ip(ip) and cidr.isdigit() and int(cidr) <= 32):
        error("invalid IP range - use CIDR notation (ex. 192.168.1.1/24)")
    cidr = int(cidr) 
    host_bits = 32 - cidr
    i = struct.unpack('>I', socket.inet_aton(ip))[0]
    start = (i >> host_bits) << host_bits
    end = start | ((1 << host_bits) - 1) 
    return [ socket.inet_ntoa(struct.pack('>I',i)) for i in range(start, end) ]

# main 
Example #29
Source File: common.py    From neverendshadowsocks with 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 #30
Source File: common.py    From neverendshadowsocks with 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