def get_interface_list(): active_interfaces = defaultdict(list) active_v4_interfaces = defaultdict(list) for adapter in ifaddr.get_adapters(): for ipaddress in adapter.ips: # If it's ipv4, it's a string. ipv6 is a tuple if isinstance(ipaddress.ip, str) and ipaddress.ip not in LOOPBACK: active_v4_interfaces[adapter.nice_name].append(ipaddress.ip) # If there is no take ipv6 instead if not active_v4_interfaces: for adapter in ifaddr.get_adapters(): for ipaddress in adapter.ips: # If it's ipv4, it's a string. ipv6 is a tuple if not isinstance(ipaddress.ip, str) and ipaddress.ip[0] not in LOOPBACK: active_interfaces[adapter.nice_name].append(ipaddress.ip[0]) else: active_interfaces = active_v4_interfaces interface_list = [] with concurrent.futures.ThreadPoolExecutor(max_workers = len(active_interfaces)) as executor: app_exec_pool = [executor.submit(get_interface_data, interface_name, active_interfaces[interface_name][0]) for interface_name in active_interfaces] for future in concurrent.futures.as_completed(app_exec_pool): interface_list.append(future.result()) for interface in interface_list: for key in interface: interface[key] = remove_non_ascii(interface[key]) return interface_list
def get_broadcast_addrs(): broadcast_addrs = [] for iface in ifaddr.get_adapters(): for addr in iface.ips: if not addr.is_IPv4: continue ip = addr.ip prefix = addr.network_prefix if ip == '127.0.0.1': continue numeric = struct.unpack( '>I', struct.pack('BBBB', *[int(x, 10) for x in ip.split('.')]))[0] mask = ~int('1' * prefix + '0' * (32 - prefix), 2) & 0xffffffff broadcast = '.'.join( str(x) for x in struct.unpack( 'BBBB', struct.pack('>I', numeric | mask))) broadcast_addrs.append(broadcast) return broadcast_addrs
def resolve_name(self, name): if name == 'localhost' or socket.gethostbyname(name) == '127.0.0.1': return set([ ip.ip for adapter in ifaddr.get_adapters() for ip in adapter.ips if isinstance(ip.ip, str) ]) return [socket.gethostbyname(name)]
def get_if_name_by_ip(if_ip): """Get interface name by interface IP""" for adapter in ifaddr.get_adapters(): for ip_ in adapter.ips: if ip_.ip == if_ip: return adapter.name raise ValueError(f"IP {if_ip} does not match any network interface!")
def get_all_addresses(): return list({ addr.ip for iface in ifaddr.get_adapters() for addr in iface.ips if addr.is_IPv4 and addr.network_prefix != 32 # Host only netmask 255.255.255.255 })
def get_addresses(): """ Get all IP addresses. Returns list of addresses. """ addresses = set() for iface in ifaddr.get_adapters(): for addr in iface.ips: # Filter out link-local addresses. if addr.is_IPv4: ip = addr.ip if not ip.startswith("169.254."): addresses.add(ip) elif addr.is_IPv6: # Sometimes, IPv6 addresses will have the interface name # appended, e.g. %eth0. Handle that. ip = addr.ip[0].split("%")[0].lower() if not ip.startswith("fe80:"): addresses.add("[{}]".format(ip)) return sorted(list(addresses))
def udpb_init_by_interface_(self, in_interface, in_ipv6 = False): if not isinstance(in_interface, str) \ or not isinstance(in_ipv6, bool): return False try: my_adapters = ifaddr.get_adapters() for my_adapter in my_adapters: my_adapter_name = my_adapter.name if isinstance(my_adapter_name, bytes): my_adapter_name = str(my_adapter_name, self.udpb_encoding) if my_adapter_name == in_interface: for my_ip in my_adapter.ips: if not in_ipv6 and self.is_ipv4_address_(my_ip.ip): self.udpb_ip = my_ip.ip my_net = ipaddress.IPv4Network(my_ip.ip \ + '/{:d}'.format(my_ip.network_prefix), strict = False) self.udpb_ip_broadcast \ = '{}'.format(my_net.broadcast_address) break elif in_ipv6 and isinstance(my_ip.ip, tuple): ( my_ipv6, my_ipv6p1, my_ipv6p2 ) = my_ip.ip if self.is_ipv6_address_(my_ipv6): self.udpb_ip = my_ipv6 break except: return False return False
def udpb_update_local_ip_addresses_(self): new_ip_addresses = [] new_ip_broadcasts = [] try: my_adapters = ifaddr.get_adapters() for my_adapter in my_adapters: for my_ip in my_adapter.ips: if self.is_ipv4_address_(my_ip.ip): new_ip_addresses += [ my_ip.ip ] my_net = ipaddress.IPv4Network(my_ip.ip \ + '/{:d}'.format(my_ip.network_prefix), strict = False) my_broadcast = '{}'.format(my_net.broadcast_address) new_ip_broadcasts += [ my_broadcast ] del my_broadcast del my_net elif isinstance(my_ip.ip, tuple): ( my_ipv6, my_ipv6_flowinfo, my_ipv6_scope_id ) = my_ip.ip if self.is_ipv6_address_(my_ipv6): new_ip_addresses += [ my_ipv6 ] if new_ip_addresses != []: self.udpb_local_ip_addresses = new_ip_addresses if new_ip_broadcasts != []: self.udpb_local_ip_broadcasts = new_ip_broadcasts except: pass
def _find_ipv4_addresses(): """Discover and return all the host's IPv4 addresses. Helper function to return a set of IPv4 addresses associated with the network interfaces of this host. Loopback and link local addresses are excluded. Returns: set: A set of IPv4 addresses (dotted decimal strings). Empty set if there are no addresses found. """ ipv4_addresses = set() for adapter in ifaddr.get_adapters(): for ifaddr_network in adapter.ips: try: ipaddress.IPv4Network(ifaddr_network.ip) except ValueError: # Not an IPv4 address continue ipv4_network = ipaddress.ip_network(ifaddr_network.ip) if not ipv4_network.is_loopback and not ipv4_network.is_link_local: ipv4_addresses.add(ifaddr_network.ip) _LOG.debug("Set of attached IPs: %s", str(ipv4_addresses)) return ipv4_addresses
def find_ipv4_networks(self): """Returns a set of IPv4 networks to which this node is attached.""" ipv4_net_list = set() adapters = ifaddr.get_adapters() for adapter in adapters: for ip in adapter.ips: if Speakers.is_ipv4_address(ip.ip): network_ip = ipaddress.ip_network(ip.ip) if network_ip.is_private and not network_ip.is_loopback: # Constrain the size of network that will be searched netmask = ip.network_prefix if netmask < self._min_netmask: logging.info( "{}: Constraining netmask={} to {}".format( ip.ip, ip.network_prefix, self._min_netmask ) ) netmask = self._min_netmask network = ipaddress.ip_network( ip.ip + "/" + str(netmask), False ) ipv4_net_list.add(network) self._networks = list(ipv4_net_list) logging.info("IPv4 networks to search: {}".format(ipv4_net_list)) return ipv4_net_list
async def _create_endpoints(self): """Create an endpoint per interface and return as a list of endpoints.""" endpoints = [] loop = asyncio.get_event_loop() listening = 0 for adapter in ifaddr.get_adapters(): for ip in adapter.ips: if ip.is_IPv4 and not ipaddress.ip_address(ip.ip).is_loopback: endpoint = SensemeDiscoveryEndpoint(ip.ip) # _LOGGER.debug("Found IPv4 %s", ip.ip) try: await loop.create_datagram_endpoint( lambda ep=endpoint: SensemeDiscoveryProtocol(ep), local_addr=(ip.ip, PORT), family=socket.AF_INET, allow_broadcast=True, ) endpoints.append(endpoint) listening += 1 except OSError: last_error = ( f"Create datagram endpoint error on {ip.ip}\n" f"{traceback.format_exc()}" ) _LOGGER.debug(last_error) if listening == 0: # failed to bind to any address _LOGGER.error( "Failed to listen for discovery responses on any address. " "Last error\n%s", last_error, ) return endpoints
def get_info(): res= {} # if backup exists add backup date bkupTime= '' file= bkupFolder+ '/info.txt' if os.path.isfile(file) and os.path.isfile(bkupFolder+ '/wpa_supplicant.conf') and os.path.isfile(bkupFolder+ '/beamOfTime/bot/app.py'): if platform.system() == 'Windows': bkupTime= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(file))) else: stat = os.stat(file) bkupTime= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat.st_mtime)) res['backup_time']= bkupTime # add hostname res['hostname']= socket.gethostname() # add all ip addresses ipaddresses= [] adapters = ifaddr.get_adapters() for adapter in adapters: aName= adapter.nice_name.lower() for ip in adapter.ips: # cleanup adapter names on windows aName= aName.replace('intel(r) ', '') aName= aName.replace('dual band wireless-ac', 'wifi') aName= aName.replace('ethernet connection ', 'eth') # exclude 'internal' adapters if type(ip.ip) == str and aName!= 'lo' and not 'virtual' in aName and not 'loopback' in aName and not 'bluetooth' in aName: ipaddresses.append({'name': aName, 'ip': ip.ip}) res['ips']= ipaddresses return jsonify(res)
def get_local_ip(host): """ The primary ifaddr based approach, tries to guess the local ip from the cc ip, by comparing the subnet of ip-addresses of all the local adapters to the subnet of the cc ip. This should work on all platforms, but requires the catt box and the cc to be on the same subnet. As a fallback we use a socket based approach, that does not suffer from this limitation, but might not work on all platforms. """ host_ipversion = type(ipaddress.ip_address(host)) for adapter in ifaddr.get_adapters(): for adapter_ip in adapter.ips: aip = adapter_ip.ip[0] if isinstance(adapter_ip.ip, tuple) else adapter_ip.ip try: if not isinstance(ipaddress.ip_address(aip), host_ipversion): continue except ValueError: continue ipt = [(ip, adapter_ip.network_prefix) for ip in (aip, host)] catt_net, cc_net = [ ipaddress.ip_network("{0}/{1}".format(*ip), strict=False) for ip in ipt ] if catt_net == cc_net: return aip else: continue try: return [(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1] except OSError: return None
def ips(): result = "" for adapter in ifaddr.get_adapters(): result = result + f'IP addressing of network adapter {adapter.nice_name}\n' for ip in adapter.ips: result = result + f' - {ip.ip}/{ip.network_prefix}\n' return Response(result, mimetype='text/plain')
def get_local_ips(): import ifaddr for adapter in ifaddr.get_adapters(): for ip in adapter.ips: if isinstance(ip.ip, str): yield ip.ip
def get_ip_choices(): """ lists the addresses and names of available network interfaces :return: list of dicts {'addr', 'name', 'prefix'} addr is the IPv4 or IPv6 network address name is the "nice" name. prefix is the number of bits in the network prefix """ adapters = ifaddr.get_adapters() rtn = [] for adapter in adapters: for ip in adapter.ips: if isinstance(ip.ip, str): # IPv4 rtn.append({ "addr": ipaddress.IPv4Address(ip.ip), "name": adapter.nice_name, "prefix": ip.network_prefix }) else: # IPv6 rtn.append({ "addr": ipaddress.IPv6Address(ip.ip[0]), "name": adapter.nice_name, "prefix": ip.network_prefix }) return rtn
def main(system, logger): """ Gets all IP addresses on interfaces and adds them to a list if they aren't local IPs and then compares the list of gathered IPs to the list of acceptable IPs """ ips = [] adapters = ifaddr.get_adapters() for adapter in adapters: for ip_info in adapter.ips: ip = ip_info.ip if type(ip) == tuple: if ip[0].startswith('fe80'): continue elif ip[0] == '::1': continue else: ips.append(ip[0]) elif ip == "127.0.0.1" or ip == "127.0.1.1": continue else: ips.append(ip) return compare(ips)
def run(): IFACE = '' adapters = list(ifaddr.get_adapters()) print("Choose an adapter:") for i in range(len(adapters)): print("{0:>2}) [{1:>18}] {2}".format( i, adapters[i].ips[0].ip + '/' + str(adapters[i].ips[0].network_prefix), adapters[i].nice_name)) choice = int(input(">>> ")) if choice in range(len(adapters)): IFACE = adapters[choice].nice_name print("Your choice: " + IFACE) else: print("Choice not in range.") exit(1) ip = adapters[choice].ips[0].ip network_prefix = adapters[choice].ips[0].network_prefix # List all address to scan addresses = ipaddress.ip_network(ip + '/' + str(network_prefix), strict=False).hosts() # Create socket sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3)) sock.bind((IFACE, 0)) for addr in addresses: data = packet_builder()
def get_loopback(): import ifaddr for adapter in ifaddr.get_adapters(): if adapter.name.startswith("lo"): return adapter.name return None
def readConfig(self): config = configparser.ConfigParser() config.read('config.ini') if config['CONFIG']['ROUTER_NAME'] == "": raise ValueError('%sconfig is not edited, please change it%s' % (fg('160'), attr('reset'))) self.routerName = config['CONFIG']['ROUTER_NAME'] self.routerPort = int(config['CONFIG']['ROUTER_PORT']) flag = True nb_neig = 1 while flag: name = "NEIGHBOR_" + str(nb_neig) try: test = config['CONFIG'][name] x = test.split(" ") neighborsTable.insertNeighbor(x[0], x[1], x[2], x[3]) nb_neig += 1 except KeyError: flag = False # TODO move this to LSDU handler to update seqNbr for each new LSDU # generated activeLinks = dict() for key, value in neighborsTable.items(): activeLinks[key] = value.linkCost linkStateDatabase.acquire() linkStateDatabase.insertEntries(self.routerName, activeLinks, 0) linkStateDatabase.release() # store all server's interface IP addresses adapters = ifaddr.get_adapters() for adapter in adapters: for ip in adapter.ips: self.ipAddresses.append(ip.ip)
def ifaddrs(): ips = set() for iface in ifaddr.get_adapters(): for ip in iface.ips: if ip.is_IPv4 and not ip.ip.startswith('127'): ips.add('{ip.ip}/{ip.network_prefix}'.format(ip=ip)) return ips
def __init__(self, interface): iface_list = ifaddr.get_adapters() for adapter in iface_list: if interface == adapter.nice_name: break else: raise AttributeError("Interface NOT found")
def get_adap_to_ip(): dict_adap = {} adapters = ifaddr.get_adapters() for adap in adapters: for ip in adap.ips: dict_adap[ip.ip] = ip.nice_name.split(':')[0] return dict_adap
def get_ip(hostname): adapters = ifaddr.get_adapters() for adapter in adapters: for ip in adapter.ips: ip = ip.ip if '192.168.' in ip: return ip return get_ip_ubuntu(hostname)
def look(self): self.ifname = ifaddr.get_adapters() self._get_ip() for ip in self.ips: _1, _2, _3, _4 = ip.split('.') for i in range(1,256): ip = (f"{_1}.{_2}.{_3}.{i}", 33333) t(target=self.connect, args=(ip)).start()
def get_local_address_reaching(dest_ip: IPv4Address) -> Optional[IPv4Address]: """Get address of a local interface within same subnet as provided address.""" for adapter in get_adapters(): for addr in [addr for addr in adapter.ips if addr.is_IPv4]: iface = IPv4Interface(f"{addr.ip}/{addr.network_prefix}") if dest_ip in iface.network: return iface.ip return None
def get_ip_info(): result = '' adapters = ifaddr.get_adapters() for adapter in adapters: result += "IPs of network adapter " + adapter.nice_name + '\n' for ip in adapter.ips: result += " %s/%s" % (ip.ip, ip.network_prefix) + '\n\n' return result
def check_interface(interface): iface_list = ifaddr.get_adapters() for adapter in iface_list: if interface == adapter.nice_name: return interface else: raise argparse.ArgumentTypeError("Interface " + interface + " NOT found")
def get_src_ip_by_dst_ip_(self, in_server_ip): my_ipv4_route = None my_ipv6_route = None if self.is_ipv4_address_(in_server_ip): my_ipv4_route = self.get_ipv4_route_(in_server_ip) if my_ipv4_route == None: return None ( my_if_name, my_network, my_netmask, \ my_metric, my_gateway ) = my_ipv4_route elif self.is_ipv6_address_(in_server_ip): my_ipv6_route = self.get_ipv6_route_(in_server_ip) if my_ipv6_route == None: return None ( my_if_name, my_network, my_netmask, \ my_metric, my_gateway ) = my_ipv6_route else: return None my_ip_out = None my_ip_mask = ipaddress.ip_address(in_server_ip) my_adapters = ifaddr.get_adapters() for my_adapter in my_adapters: for my_ip in my_adapter.ips: if self.is_ipv4_address_(my_ip.ip) \ and my_ipv4_route != None: my_network_str \ = "{}/{:d}".format(my_ip.ip, my_ip.network_prefix) my_netbase = ipaddress.ip_network(my_network_str, False) if my_ip_mask in my_netbase: return my_ip.ip if my_adapter.name == my_if_name: if my_gateway == None: my_ip_out = my_ip.ip else: my_netbase = ipaddress.ip_network(my_network \ + '/' + my_netmask) my_ip_check = ipaddress.ip_address(my_ip.ip) if my_ip_check in my_netbase: return my_ip.ip elif isinstance(my_ip.ip, tuple) \ and my_ipv6_route != None: (my_ipv6, my_ipv6_flowinfo, my_ipv6_scope_id) = my_ip.ip if self.is_ipv6_address_(my_ipv6): my_network_str \ = "{}/{:d}".format(my_ipv6, my_ip.network_prefix) my_netbase = ipaddress.ip_network( my_network_str, False) if my_ip_mask in my_netbase: return my_ipv6 if my_adapter.name == my_if_name: if my_gateway == None: my_ip_out = my_ipv6 else: my_netbase = ipaddress.ip_network(my_network \ + "/{:d}".format(my_netmask), False) my_ip_check = ipaddress.ip_address(my_ipv6) if my_ip_check in my_netbase: return my_ipv6 return my_ip_out
def GetIp(interface): adapters = ifaddr.get_adapters() temp = "" for adapter in adapters: if (adapter.nice_name == interface): temp = adapter.ips[0].ip return temp
def findip(self): adapters = ifaddr.get_adapters() print "**************************** LOCAL ADAPTERS ***********************************" for adapter in adapters: print "IPs of network adapter " + adapter.nice_name for ip in adapter.ips: print "%s/%s" % (ip.ip, ip.network_prefix) print "************************** NEIGHBOURS CONNECTED *******************************" from ipadd import * scan_and_print_neighbors(net, interface)
def test_get_adapters_contains_localhost(self): found = False adapters = ifaddr.get_adapters() for adapter in adapters: for ip in adapter.ips: if ip.ip == "127.0.0.1": found = True self.assertTrue(found, "No adapter has IP 127.0.0.1: %s" % str(adapters))
def get_local_ip(host): for adapter in ifaddr.get_adapters(): for adapter_ip in adapter.ips: aip = adapter_ip.ip[0] if isinstance(adapter_ip.ip, tuple) else adapter_ip.ip try: if not isinstance(ipaddress.ip_address(host), type(ipaddress.ip_address(aip))): raise ValueError except ValueError: continue ipt = [(ip, adapter_ip.network_prefix) for ip in (aip, host)] catt_net, cc_net = [ipaddress.ip_network("%s/%s" % ip, strict=False) for ip in ipt] if catt_net == cc_net: return aip else: continue
def get_adapter(private_ip): adapters = ifaddr.get_adapters() for adapter in adapters: for ip in adapter.ips: if ip.ip == private_ip: return adapter.nice_name
# -*- coding: utf-8 -*- """ Created on Tue Oct 31 06:54:31 2017 @author: mtkes """ import ifaddr adapters = ifaddr.get_adapters() for adapter in adapters: print("IPs of network adapter " + adapter.nice_name) for ip in adapter.ips: print(" %s/%s" % (ip.ip, ip.network_prefix))