def get_ip_address(self, test_address=None): """ try to get global IP address from interface information. if failed, just return '127.0.0.1' :param str test_address: ip address str if test to check global ip. normally None. :return: global ip address if successed, or '127.0.0.1' """ for iface_name in netifaces.interfaces(): iface_data = netifaces.ifaddresses(iface_name) logging.debug('Interface: %s' % (iface_name, )) ifaces = [] if netifaces.AF_INET in iface_data: ifaces += iface_data[netifaces.AF_INET] if netifaces.AF_INET6 in iface_data: ifaces += iface_data[netifaces.AF_INET6] for iface in ifaces: ip = iface['addr'] ip = re.sub(r'\%.+$', '', ip) if test_address is not None: ip = test_address addr = IPAddress(ip) if not addr.is_loopback() and addr.is_unicast() and\ not addr.is_private(): logging.debug('global ip %s', addr) return ip logging.debug('no global ip') return '127.0.0.1'
def check_ip_address(ipaddr): ip_attributes = [] ipaddress = IPAddress(ipaddr) if ipaddress.is_private(): ip_attributes.append("IP Address is Private") else: ip_attributes.append("IP Address is public") if ipaddress.is_unicast(): ip_attributes.append("IP Address is unicast") elif ipaddress.is_multicast(): ip_attributes.append("IP Address is multicast") if ipaddress.is_loopback(): ip_attributes.append("IP Address is loopback") return "\n".join(ip_attributes)
def validate_ip_address (address, netmask, gateway = None): """ Validate that the provided IP settings are valid. :param address: The IP address that will be assigned to the interface. :param netmask: The subnet mask for the interface. :param gateway: The default gateway to use for the system. """ ip = IPAddress (address) if (not ip.is_unicast () or ip.is_loopback () or ip.is_reserved ()): raise ValueError ("IP address is not a valid host address.") if (not IPAddress (netmask).is_netmask ()): raise ValueError ("Subnet mask is not valid.") subnet = IPNetwork (address, netmask) if gateway: route = IPNetwork (gateway, netmask) if (subnet != route): raise ValueError ("Gateway supplied is not on the specified subnet.")
def _is_public(self, ip): ip = IPAddress(ip) return ip.is_unicast() and not ip.is_private()
def reserved_ip_check(ip_string): """determine if IP address in RFC1918 or reserved""" # IP details for invalid IP addresses invalid_ip_details = { "country": "INVALID", "location": RESERVED_IP_COORDINATES, "subdivisions": "INVALID", "dch_company": "", "asn_number": "", "asn_name": "" } # IP details for MULTICAST IP addresses multicast_ip_details = { "country": "MULTICAST", "location": RESERVED_IP_COORDINATES, "subdivisions": "MULTICAST", "dch_company": "", "asn_number": "", "asn_name": "" } # IP details for PRIVATE IP addresses private_ip_details = { "country": "PRIVATE", "location": RESERVED_IP_COORDINATES, "subdivisions": "PRIVATE", "dch_company": "", "asn_number": "", "asn_name": "" } # IP details for RESERVED IP addresses reserved_ip_details = { "country": "RESERVED", "location": RESERVED_IP_COORDINATES, "subdivisions": "RESERVED", "dch_company": "", "asn_number": "", "asn_name": "" } # IP details for NETMASK IP addresses netmask_ip_details = { "country": "NETMASK", "location": RESERVED_IP_COORDINATES, "subdivisions": "NETMASK", "dch_company": "", "asn_number": "", "asn_name": "" } # IP details for HOSTMASK IP addresses hostmask_ip_details = { "country": "HOSTMASK", "location": RESERVED_IP_COORDINATES, "subdivisions": "HOSTMASK", "dch_company": "", "asn_number": "", "asn_name": "" } # IP details for LOOPBACK IP addresses loopback_ip_details = { "country": "LOOPBACK", "location": RESERVED_IP_COORDINATES, "subdivisions": "LOOPBACK", "dch_company": "", "asn_number": "", "asn_name": "" } # Check to see if IP matches a reserved category try: ip_address = IPAddress(ip_string) except AddrFormatError: return invalid_ip_details if ip_address.is_multicast(): return multicast_ip_details elif ip_address.is_private(): return private_ip_details elif ip_address.is_reserved(): return reserved_ip_details elif ip_address.is_netmask(): return netmask_ip_details elif ip_address.is_hostmask(): return hostmask_ip_details elif ip_address.is_loopback(): return loopback_ip_details elif ip_address.is_unicast() and not ip_address.is_private(): # Boolean to be returned if IP is Public ip_reserved = False return ip_reserved else: return invalid_ip_details
def fifoReader(infile, q, exitSignal): sleeptime = 0.5 maxSleeptime = 1.0 while True: try: if exitSignal.is_set(): break line = infile.readline() if not line: time.sleep(1) continue if line == 'ENDOFFILE': break try: spl = line.split() timestamp, queriedName, clientID, ipv4 = spl except: continue else: if not '.' in queriedName: continue try: addr = IPAddress(ipv4) except netaddr.AddrFormatError: continue else: if (addr.is_unicast() and not addr.is_private() and not addr.is_reserved() and not addr.is_loopback()): try: timestamp = int(timestamp) except ValueError: continue else: data = ((queriedName, clientID, [addr]), timestamp) queued = False while not queued: try: q.put_nowait(data) except Queue.Full: # we saturated the queue, let's give the reading # process some time to empty it again, where we don't # try to put something in the queue and thereby lock it # continuously time.sleep(sleeptime) if q.empty(): sleeptime *= 0.5 elif q.qsize() >= q._maxsize: sleeptime *= 2 if sleeptime > maxSleeptime: sleeptime = maxSleeptime else: queued = True except KeyboardInterrupt: break q.put(None)
def pcapReader(q, exitSignal, infile=None, interface=None, thrsh=0): if not infile and not interface: # FIXME: write warning here return if infile: pc = pcap.pcapObject() try: pc.open_offline(infile) except IOError: #log("could not open pcap interface "+str(input_interface)+"\n") pass if interface: pc = pcap.pcapObject() try: #pc.open_live(interface, snaplen, promisc, read_timeout) pc.open_live(interface, 1600, 0, 100) except IOError: #log("could not open pcap interface "+str(input_interface)+"\n") pass except Exception: # most likely we got no permission to open the interface sys.stderr.write('could not open interface. insufficient ' 'permissions?\n') q.put(None) return pc.setfilter('udp', 0, 0) basets = 0 newMappings = dict() while True: if exitSignal.is_set(): break try: packet = pc.next() if not packet: if infile: # end of file break elif interface: # read timeout continue payload = packet[1] timestamp = int(packet[2]) # make sure we are dealing with IP traffic # ref: http://www.iana.org/assignments/ethernet-numbers try: eth = dpkt.ethernet.Ethernet(payload) except: continue if eth.type != 2048: continue # make sure we are dealing with UDP # ref: http://www.iana.org/assignments/protocol-numbers/ try: ip = eth.data except: continue if ip.p != 17: continue # filter on UDP assigned ports for DNS # ref: http://www.iana.org/assignments/port-numbers try: udp = ip.data except: continue if udp.sport != 53 and udp.dport != 53: continue # make the dns object out of the udp data and check for it being a RR (answer) # and for opcode QUERY (I know, counter-intuitive) try: dns = dpkt.dns.DNS(udp.data) except: continue if dns.qr != dpkt.dns.DNS_R: continue if dns.opcode != dpkt.dns.DNS_QUERY: continue if dns.rcode != dpkt.dns.DNS_RCODE_NOERR: continue if len(dns.an) < 1: continue if len(dns.qd) == 0: continue aRecords = set() queriedName = dns.qd[0].name if not '.' in queriedName: continue #lastCname=queriedName for answer in dns.an: """ FIXME: this doesn't work for multiple queries in one DNS packet """ #if answer.type == dpkt.dns.DNS_CNAME: # lastCname=answer.cname if answer.type == dpkt.dns.DNS_A: ip = socket.inet_ntoa(answer.rdata) try: addr = IPAddress(ip) except netaddr.AddrFormatError: continue else: if (addr.is_unicast() and not addr.is_private() and not addr.is_reserved() and not addr.is_loopback()): aRecords.add(addr) if thrsh: if (timestamp - basets) > thrsh: basets = timestamp newMappings.clear() newIps = checkMapping(newMappings, queriedName, aRecords) aRecords = newIps if not aRecords: continue data = ((queriedName, ip.dst, aRecords), timestamp) queued = False while not queued: try: q.put_nowait(data) except Queue.Full: # we saturated the queue, let's give the reading # process some time to empty it again, where we don't # try to put something in the queue and thereby lock it # continuously time.sleep(sleeptime) if q.empty(): sleeptime *= 0.5 elif q.qsize() >= q._maxsize: sleeptime *= 2 if sleeptime > maxSleeptime: sleeptime = maxSleeptime else: queued = True except KeyboardInterrupt: break """ send shutdown signal """ q.put(None)
def has_public_ip(self): ip = IPAddress(self.ip) return ip.is_unicast() and not ip.is_private()
def fifoReader(infile, q, exitSignal): sleeptime=0.5 maxSleeptime=1.0 while True: try: if exitSignal.is_set(): break line=infile.readline() if not line: time.sleep(1) continue if line=='ENDOFFILE': break try: spl=line.split() timestamp, queriedName, clientID, ipv4 = spl except: continue else: if not '.' in queriedName: continue try: addr=IPAddress(ipv4) except netaddr.AddrFormatError: continue else: if (addr.is_unicast() and not addr.is_private() and not addr.is_reserved() and not addr.is_loopback()): try: timestamp=int(timestamp) except ValueError: continue else: data = ((queriedName, clientID, [addr]), timestamp) queued=False while not queued: try: q.put_nowait(data) except Queue.Full: # we saturated the queue, let's give the reading # process some time to empty it again, where we don't # try to put something in the queue and thereby lock it # continuously time.sleep(sleeptime) if q.empty(): sleeptime*=0.5 elif q.qsize() >= q._maxsize: sleeptime*=2 if sleeptime>maxSleeptime: sleeptime=maxSleeptime else: queued=True except KeyboardInterrupt: break q.put(None)
def pcapReader(q, exitSignal, infile=None, interface=None, thrsh=0): if not infile and not interface: # FIXME: write warning here return if infile: pc=pcap.pcapObject() try: pc.open_offline(infile) except IOError: #log("could not open pcap interface "+str(input_interface)+"\n") pass if interface: pc=pcap.pcapObject() try: #pc.open_live(interface, snaplen, promisc, read_timeout) pc.open_live(interface, 1600, 0, 100) except IOError: #log("could not open pcap interface "+str(input_interface)+"\n") pass except Exception: # most likely we got no permission to open the interface sys.stderr.write('could not open interface. insufficient ' 'permissions?\n') q.put(None) return pc.setfilter('udp', 0, 0) basets=0 newMappings=dict() while True: if exitSignal.is_set(): break try: packet=pc.next() if not packet: if infile: # end of file break elif interface: # read timeout continue payload=packet[1] timestamp=int(packet[2]) # make sure we are dealing with IP traffic # ref: http://www.iana.org/assignments/ethernet-numbers try: eth = dpkt.ethernet.Ethernet(payload) except: continue if eth.type != 2048: continue # make sure we are dealing with UDP # ref: http://www.iana.org/assignments/protocol-numbers/ try: ip = eth.data except: continue if ip.p != 17: continue # filter on UDP assigned ports for DNS # ref: http://www.iana.org/assignments/port-numbers try: udp = ip.data except: continue if udp.sport != 53 and udp.dport != 53: continue # make the dns object out of the udp data and check for it being a RR (answer) # and for opcode QUERY (I know, counter-intuitive) try: dns = dpkt.dns.DNS(udp.data) except: continue if dns.qr != dpkt.dns.DNS_R: continue if dns.opcode != dpkt.dns.DNS_QUERY: continue if dns.rcode != dpkt.dns.DNS_RCODE_NOERR: continue if len(dns.an) < 1: continue if len(dns.qd) == 0: continue aRecords=set() queriedName=dns.qd[0].name if not '.' in queriedName: continue #lastCname=queriedName for answer in dns.an: """ FIXME: this doesn't work for multiple queries in one DNS packet """ #if answer.type == dpkt.dns.DNS_CNAME: # lastCname=answer.cname if answer.type == dpkt.dns.DNS_A: ip=socket.inet_ntoa(answer.rdata) try: addr=IPAddress(ip) except netaddr.AddrFormatError: continue else: if (addr.is_unicast() and not addr.is_private() and not addr.is_reserved() and not addr.is_loopback()): aRecords.add(addr) if thrsh: if (timestamp-basets) > thrsh: basets = timestamp newMappings.clear() newIps = checkMapping(newMappings, queriedName, aRecords) aRecords=newIps if not aRecords: continue data = ((queriedName, ip.dst, aRecords), timestamp) queued=False while not queued: try: q.put_nowait(data) except Queue.Full: # we saturated the queue, let's give the reading # process some time to empty it again, where we don't # try to put something in the queue and thereby lock it # continuously time.sleep(sleeptime) if q.empty(): sleeptime*=0.5 elif q.qsize() >= q._maxsize: sleeptime*=2 if sleeptime>maxSleeptime: sleeptime=maxSleeptime else: queued=True except KeyboardInterrupt: break """ send shutdown signal """ q.put(None)
def check_ip(dns_result: str) -> bool: addr = IPAddress(dns_result) if ((not addr.is_unicast()) or addr.is_private() or addr.is_loopback() or addr.is_link_local()): return False return True
def ping(self, targets=list(), filename=str(), status=str(), notDNS=False, elapsed=False ): """ Attempt to ping a list of hosts or networks (can be a single host) :param targets: List - Name(s) or IP(s) of the host(s). :param filename: String - name of the file containing hosts to ping :param status: String - if one of ['alive', 'dead', 'noip'] then only return results that have that status. If this is not specified, then all results will be returned. :param notDNS: Bolean - If True turn on use of -A option for fping for not use dns resolve names. Default is False. :param elapsed: Bolean - If True turn on use of -e option for fping for show elapsed time on return packets. Default is False. :return: Type and results depends on whether status is specified: if status == '': return dict: {targets: results} if status != '': return list: targets if targets == status """ if targets and filename: raise SyntaxError("You must specify only one of either targets=[] " "or filename=''.") elif not targets and not filename: raise SyntaxError("You must specify either a list of targets or " "filename='', but not both.") elif filename: targets = self.read_file(filename) my_targets = {'hosts': [], 'nets': []} addresses = [] # Check for valid networks and add hosts and nets to my_targets for target in targets: # Targets may include networks in the format "network mask", or, # a file could contain multiple hosts or IP's on a single line. if len(target.split()) > 1: target_items = target.split() for item in target_items: try: ip = IPAddress(item) # If it is an IPv4 address or mask put in in addresses if ip.version == 4: addresses.append(str(ip)) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(item) except ValueError: # CIDR network detected net = IPNetwork(item) # Make sure it is a CIDR address acceptable to fping if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target_items[0]) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) # Iterate over the IP strings in addresses while len(addresses) > 1: ip = IPAddress(addresses[0]) mask = IPAddress(addresses[1]) # Test to see if IP is unicast, and mask is an actual mask if ip.is_unicast() and mask.is_netmask(): net = IPNetwork(str(ip) + '/' + str( mask.netmask_bits())) # Convert ip and mask to CIDR and remove from addresses my_targets['nets'].append(str(net.cidr)) addresses.pop(0) addresses.pop(0) elif ip.is_unicast() and not ip.is_netmask(): # mask was not a mask so only remove IP and start over my_targets['hosts'].append(str(ip)) addresses.pop(0) # There could be one more item in addresses, so check it if addresses: ip = IPAddress(addresses[0]) if ip.is_unicast() and not ip.is_netmask(): my_targets['hosts'].append(addresses[0]) addresses.pop() # target has only one item, so check it else: try: ip = IPAddress(target) if ip.version == 4 and ip.is_unicast() and \ not ip.is_netmask(): my_targets['hosts'].append(target) else: msg = str(target + 'Only IPv4 unicast addresses are ' 'supported.') raise AttributeError(msg) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(target) except ValueError: # CIDR network detected net = IPNetwork(target) if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) """ Build the list of common options for commands to run. """ options = '-V' # This is for default if notDNS: options += 'A' # show targets by ip else: options += 'n' # show target by name if elapsed: options += 'e' # show elapsed time on return packets """ Build the list of commands to run. """ commands = [] if len(my_targets['hosts']) != 0: for target in range(len(my_targets['hosts'])): commands.append([self.fping, options, my_targets['hosts'][ target]]) if len(my_targets['nets']) != 0: for target in range(len(my_targets['nets'])): netops = options + 'g' # generate target list for net target commands.append([self.fping, netops, my_targets['nets'][ target]]) """ Start pinging each item in my_targets and return the requested results when done. """ pool = ThreadPool(self.num_pools) raw_results = pool.map(self.get_results, commands) pool.close() pool.join() self.results = {line[0]: line[2:] for line in csv.reader( ''.join(raw_results).splitlines())} if not status: return self.results elif status == 'alive': return self.alive elif status == 'dead': return self.dead elif status == 'noip': return self.noip else: raise SyntaxError("Valid status options are 'alive', 'dead' or " "'noip'")
def ping(self, targets=list(), filename=str(), status=str()): """ Attempt to ping a list of hosts or networks (can be a single host) :param targets: List - Name(s) or IP(s) of the host(s). :param filename: String - name of the file containing hosts to ping :param status: String - if one of ['alive', 'dead', 'noip'] then only return results that have that status. If this is not specified, then all results will be returned. :return: Type and results depends on whether status is specified: if status == '': return dict: {targets: results} if status != '': return list: targets if targets == status """ if targets and filename: raise SyntaxError("You must specify only one of either targets=[] " "or filename=''.") elif not targets and not filename: raise SyntaxError("You must specify either a list of targets or " "filename='', but not both.") elif filename: targets = self.read_file(filename) my_targets = {'hosts': [], 'nets': []} addresses = [] # Check for valid networks and add hosts and nets to my_targets for target in targets: # Targets may include networks in the format "network mask", or, # a file could contain multiple hosts or IP's on a single line. if len(target.split()) > 1: target_items = target.split() for item in target_items: try: ip = IPAddress(item) # If it is an IPv4 address or mask put in in addresses if ip.version == 4: addresses.append(str(ip)) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(item) except ValueError: # CIDR network detected net = IPNetwork(item) # Make sure it is a CIDR address acceptable to fping if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target_items[0]) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) # Iterate over the IP strings in addresses while len(addresses) > 1: ip = IPAddress(addresses[0]) mask = IPAddress(addresses[1]) # Test to see if IP is unicast, and mask is an actual mask if ip.is_unicast() and mask.is_netmask(): net = IPNetwork(str(ip) + '/' + str( mask.netmask_bits())) # Convert ip and mask to CIDR and remove from addresses my_targets['nets'].append(str(net.cidr)) addresses.pop(0) addresses.pop(0) elif ip.is_unicast() and not ip.is_netmask(): # mask was not a mask so only remove IP and start over my_targets['hosts'].append(str(ip)) addresses.pop(0) # There could be one more item in addresses, so check it if addresses: ip = IPAddress(addresses[0]) if ip.is_unicast() and not ip.is_netmask(): my_targets['hosts'].append(addresses[0]) addresses.pop() # target has only one item, so check it else: try: ip = IPAddress(target) if ip.version == 4 and ip.is_unicast() and \ not ip.is_netmask(): my_targets['hosts'].append(target) else: msg = str(target + 'Only IPv4 unicast addresses are ' 'supported.') raise AttributeError(msg) except AddrFormatError: # IP Address not detected, so assume it's a host name my_targets['hosts'].append(target) except ValueError: # CIDR network detected net = IPNetwork(target) if net.ip.is_unicast() and net.version == 4 and \ net.netmask.netmask_bits() in range(8, 31): my_targets['nets'].append(target) else: msg = str(str(net) + ':Only IPv4 unicast addresses' ' with bit masks\n ' ' from 8 to 30 are supported.') raise AttributeError(msg) """ Build the list of commands to run. """ commands = [] if len(my_targets['hosts']) != 0: for target in range(len(my_targets['hosts'])): commands.append([self.fping, '-V', my_targets['hosts'][ target]]) if len(my_targets['nets']) != 0: for target in range(len(my_targets['nets'])): commands.append([self.fping, '-gV', my_targets['nets'][ target]]) """ Start pinging each item in my_targets and return the requested results when done. """ try: pool = ThreadPool(len(commands)) raw_results = pool.map(self.get_results, commands) self.results = {host: result for host, result in csv.reader( ''.join(raw_results).splitlines())} if not status: return self.results elif status == 'alive': return self.alive elif status == 'dead': return self.dead elif status == 'noip': return self.noip else: raise SyntaxError("Valid status options are 'alive', 'dead' or " "'noip'") finally: pool.close() pool.join()
import netaddr import socket from netaddr import IPAddress # Allow user input for ip print("what is the ip?") addr = input() # reverse DNS dns = socket.gethostbyaddr(addr) # Define ip ip = IPAddress(addr) # Print info print("IP version -", ip.version) print("private -", ip.is_private()) print("unicast -", ip.is_unicast()) print("multicast -", ip.is_multicast()) print("IP in bits -", ip.bits()) print("reverse dns -", dns)
def isPublic(ipAddr): myIpAddr = IPAddress(ipAddr) # unicast and not private return myIpAddr.is_unicast() and not myIpAddr.is_private()
""" IPAddress from netaddr in Python Please Subscribe to Asim Code. YouTube Channel: Asim Code https://youtu.be/gMtBiNjgeKE """ from netaddr import IPAddress ip = IPAddress('192.168.56.1') print(ip.version) print(ip.bin) print(ip.bits()) print(ip.words) print(ip.is_unicast()) print(ip.is_link_local())
def validate_ip(self, ip): ip = IPAddress(ip) if ip.is_unicast() and not ip.is_private(): return True else: return False
def test_is_public(): ip = IPAddress('62.125.24.5') assert ip.is_unicast() and not ip.is_private()