Python socket.inet_ntoa() Examples

The following are 30 code examples for showing how to use socket.inet_ntoa(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

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

Example 1
Project: Paradrop   Author: ParadropLabs   File: addresses.py    License: 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 2
Project: firmanal   Author: kyechou   File: makeNetwork.py    License: 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 3
Project: pynmap   Author: the-c0d3r   File: ip.py    License: GNU General Public License v3.0 6 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 4
Project: optitrack   Author: crigroup   File: utils.py    License: 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 5
Project: stem   Author: torproject   File: network.py    License: 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 6
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 7
Project: dgl   Author: dmlc   File: rpc_client.py    License: 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 8
Project: Gurux.DLMS.Python   Author: Gurux   File: GXDLMSIp4Setup.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setValue(self, settings, e):
        if e.index == 1:
            self.logicalName = _GXCommon.toLogicalName(e.value)
        elif e.index == 2:
            if isinstance(e.value, str):
                self.dataLinkLayerReference = e.value
            else:
                self.dataLinkLayerReference = _GXCommon.toLogicalName(e.value)
        elif e.index == 3:
            self.ipAddress = socket.inet_ntoa(struct.pack("!I", e.value))
        elif e.index == 4:
            self.multicastIPAddress = []
            if e.value:
                for it in e.value:
                    self.multicastIPAddress.append(socket.inet_ntoa(struct.pack("!I", it)))
        elif e.index == 5:
            self.ipOptions = []
            if e.value:
                for it in e.value:
                    item = GXDLMSIp4SetupIpOption()
                    item.type_ = it[0]
                    item.length = it[1]
                    item.data = it[2]
                    self.ipOptions.append(item)
        elif e.index == 6:
            self.subnetMask = socket.inet_ntoa(struct.pack("!I", e.value))
        elif e.index == 7:
            self.gatewayIPAddress = socket.inet_ntoa(struct.pack("!I", e.value))
        elif e.index == 8:
            self.useDHCP = e.value
        elif e.index == 9:
            self.primaryDNSAddress = socket.inet_ntoa(struct.pack("!I", e.value))
        elif e.index == 10:
            self.secondaryDNSAddress = socket.inet_ntoa(struct.pack("!I", e.value))
        else:
            e.error = ErrorCode.READ_WRITE_DENIED 
Example 9
Project: iSDX   Author: sdn-ixp   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def parse_arp_packet(packet):
    arp_detailed = struct.unpack("2s2s1s1s2s6s4s6s4s", packet)

    arp_packet = {"htype": arp_detailed[0],
                  "ptype": arp_detailed[1],
                  "hlen": arp_detailed[2],
                  "plen": arp_detailed[3],
                  "oper": arp_detailed[4],
                  "src_mac": ':'.join('%02x' % ord(b) for b in arp_detailed[5]),
                  "src_ip": socket.inet_ntoa(arp_detailed[6]),
                  "dst_mac": ':'.join('%02x' % ord(b) for b in arp_detailed[7]),
                  "dst_ip": socket.inet_ntoa(arp_detailed[8])}

    return arp_packet 
Example 10
Project: iSDX   Author: sdn-ixp   File: decision_process.py    License: Apache License 2.0 5 votes vote down vote up
def long_to_ip(ip):
    return socket.inet_ntoa(struct.pack('!L', ip)) 
Example 11
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 12
Project: smbprotocol   Author: jborean93   File: exceptions.py    License: MIT License 5 votes vote down vote up
def get_ipaddress(self):
        # get's the IP address in a human readable format
        ip_address = self['ip_address'].get_value()
        if self['type'].get_value() == IpAddrType.MOVE_DST_IPADDR_V4:
            return socket.inet_ntoa(ip_address)
        else:
            addr = binascii.hexlify(ip_address).decode('utf-8')
            return ":".join([addr[i:i + 4] for i in range(0, len(addr), 4)]) 
Example 13
Project: smbprotocol   Author: jborean93   File: ioctl.py    License: MIT License 5 votes vote down vote up
def get_ipaddress(self):
        addr_bytes = self['ipv4_address'].get_value()
        return socket.inet_ntoa(addr_bytes) 
Example 14
Project: Paradrop   Author: ParadropLabs   File: addresses.py    License: Apache License 2.0 5 votes vote down vote up
def incIpaddr(ipaddr, inc=1):
    """
        Takes a quad dot format IP address string and adds the @inc value to it by converting it to a number.

        Returns:
            Incremented quad dot IP string or None if error
    """
    try:
        val = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
        val += inc
        return socket.inet_ntoa(struct.pack('!I', val))
    except Exception:
        return None 
Example 15
Project: Paradrop   Author: ParadropLabs   File: addresses.py    License: Apache License 2.0 5 votes vote down vote up
def getSubnet(ipaddr, netmask):
    try:
        val1 = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
        nm = struct.unpack("!I", socket.inet_aton(netmask))[0]
        res = val1 & nm
        return socket.inet_ntoa(struct.pack('!I', res))
    except Exception:
        return None 
Example 16
Project: jawfish   Author: war-and-code   File: utils.py    License: 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 17
Project: Vxscan   Author: al0ne   File: random_header.py    License: Apache License 2.0 5 votes vote down vote up
def get_ua():
    ua = UserAgent()
    key = random.random() * 20
    referer = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(int(key))])
    referer = 'www.' + referer.lower() + '.com'
    ip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
    HEADERS["User-Agent"] = ua.random
    HEADERS["Referer"] = referer
    HEADERS["X-Forwarded-For"] = HEADERS["X-Real-IP"] = ip

    return HEADERS 
Example 18
Project: piescan   Author: m57   File: piescan.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sniffer_thread(target):

    sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    sniffer.bind(("0.0.0.0", 0 ))
    sniffer.settimeout(5)
    sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    # continually read in packets and parse their information
    while ( 1 ):
	try:
	        raw_buffer = sniffer.recvfrom(65565)[0]
        
	except:
		if (SNIFF_MUTEX == 0):
			sys.exit(1)

	ip_header = raw_buffer[0:20]
	dst_port = struct.unpack(">h", raw_buffer[0x32:0x34])[0]
        iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)

        # Create our IP structure
        version_ihl = iph[0]
        ihl = version_ihl & 0xF
        iph_length = ihl * 4
        src_addr = socket.inet_ntoa(iph[8]);

        # Create our ICMP structure
        buf = raw_buffer[iph_length:iph_length + ctypes.sizeof(ICMP)]
        icmp_header = ICMP(buf)

        # check for the type 3 and code and within our target subnet
        if icmp_header.code == 3 and icmp_header.type == 3 and src_addr == target:
		if dst_port not in ports_ident["closed"]:
			ports_ident["closed"].append(dst_port) 
Example 19
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    License: GNU General Public License v3.0 5 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 20
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    License: GNU General Public License v3.0 5 votes vote down vote up
def modifyUdpPacket(data, ipHeaderLength, srcAddr=None, srcPort=None, dstAddr=None, dstPort=None):
        srcAddr = srcAddr if srcAddr else socket.inet_ntoa(data[12:16])
        dstAddr = dstAddr if dstAddr else socket.inet_ntoa(data[16:20])

        srcPort = srcPort if srcPort else struct.unpack('!H', data[ipHeaderLength+0:ipHeaderLength+2])[0]
        dstPort = dstPort if dstPort else struct.unpack('!H', data[ipHeaderLength+2:ipHeaderLength+4])[0]

        # Recreate the packet
        ipHeader = data[:ipHeaderLength-8] + socket.inet_aton(srcAddr) + socket.inet_aton(dstAddr)

        udpData = data[ipHeaderLength+8:]
        udpLength = 8 + len(udpData)
        udpHeader = struct.pack('!4H', srcPort, dstPort, udpLength, 0)

        return ipHeader + udpHeader + udpData 
Example 21
Project: multicast-relay   Author: alsmith   File: multicast-relay.py    License: GNU General Public License v3.0 5 votes vote down vote up
def cidrToNetmask(bits):
        return socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << (32 - bits)))) 
Example 22
Project: gist-alfred   Author: danielecook   File: utils.py    License: 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

    :rtype: str
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits)) 
Example 23
Project: SimpleSniffer   Author: HatBoy   File: Sniffer.py    License: 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, struct.pack('256s', ifname[:15]))[20:24])

#嗅探 
Example 24
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser 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 25
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser 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 26
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser 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 27
Project: Jtyoui   Author: jtyoui   File: gateway.py    License: MIT License 5 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 28
Project: plugin.video.kmediatorrent   Author: jmarth   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
        
        # If the given destination address is an IP address, we'll
        # use the IPv4 address request even if remote resolving was specified.
        try:
            addr_bytes = socket.inet_aton(host)
            file.write(b"\x01" + addr_bytes)
            host = socket.inet_ntoa(addr_bytes)
        except socket.error:
            # Well it's not an IP number, so it's probably a DNS name.
            if rdns:
                # Resolve remotely
                file.write(b"\x03" + chr(len(host)).encode() + host.encode())
            else:
                # Resolve locally
                addr_bytes = socket.inet_aton(socket.gethostbyname(host))
                file.write(b"\x01" + addr_bytes)
                host = socket.inet_ntoa(addr_bytes)

        file.write(struct.pack(">H", port))
        return host, port 
Example 29
Project: plugin.video.kmediatorrent   Author: jmarth   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))
        else:
            raise GeneralProxyError("SOCKS5 proxy server sent invalid data")

        port = struct.unpack(">H", self._readall(file, 2))[0]
        return addr, port 
Example 30
Project: core   Author: getavalon   File: utils.py    License: 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

    :rtype: str
    """
    bits = 0xffffffff ^ (1 << 32 - mask) - 1
    return socket.inet_ntoa(struct.pack('>I', bits))