Python netifaces.gateways() Examples
The following are 30
code examples of netifaces.gateways().
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
netifaces
, or try the search function
.
Example #1
Source File: nfqueue.py From packet-queue with Apache License 2.0 | 7 votes |
def configure(protocol, port, pipes, interface): remove_all() reactor.addSystemEventTrigger('after', 'shutdown', remove_all) # gets default (outward-facing) network interface (e.g. deciding which of # eth0, eth1, wlan0 is being used by the system to connect to the internet) if interface == "auto": interface = netifaces.gateways()['default'][netifaces.AF_INET][1] else: if interface not in netifaces.interfaces(): raise ValueError("Given interface does not exist.", interface) add(protocol, port, interface) manager = libnetfilter_queue.Manager() manager.bind(UP_QUEUE, packet_handler(manager, pipes.up)) manager.bind(DOWN_QUEUE, packet_handler(manager, pipes.down)) reader = abstract.FileDescriptor() reader.doRead = manager.process reader.fileno = lambda: manager.fileno reactor.addReader(reader)
Example #2
Source File: knxip_interface.py From xknx with MIT License | 6 votes |
def start_automatic(self, scan_filter: GatewayScanFilter): """Start GatewayScanner and connect to the found device.""" gatewayscanner = GatewayScanner(self.xknx, scan_filter=scan_filter) gateways = await gatewayscanner.scan() if not gateways: raise XKNXException("No Gateways found") gateway = gateways[0] if gateway.supports_tunnelling and \ scan_filter.routing is not True: await self.start_tunnelling(gateway.local_ip, gateway.ip_addr, gateway.port, self.connection_config.auto_reconnect, self.connection_config.auto_reconnect_wait) elif gateway.supports_routing: bind_to_multicast_addr = get_os_name() != "Darwin" # = Mac OS await self.start_routing(gateway.local_ip, bind_to_multicast_addr)
Example #3
Source File: smb-autopwn.py From smb-autopwn with MIT License | 6 votes |
def get_iface(): ''' Gets the right interface ''' try: iface = netifaces.gateways()['default'][netifaces.AF_INET][1] except: ifaces = [] for iface in netifaces.interfaces(): # list of ipv4 addrinfo dicts ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, []) for entry in ipv4s: addr = entry.get('addr') if not addr: continue if not (iface.startswith('lo') or addr.startswith('127.')): ifaces.append(iface) iface = ifaces[0] return iface
Example #4
Source File: MsfWrapper.py From MsfWrapper with MIT License | 6 votes |
def get_iface(self): ''' Gets the interface with an IP address connected to a default gateway ''' try: iface = netifaces.gateways()['default'][netifaces.AF_INET][1] except: ifaces = [] for iface in netifaces.interfaces(): # list of ipv4 addrinfo dicts ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, []) for entry in ipv4s: addr = entry.get('addr') if not addr: continue if not (iface.startswith('lo') or addr.startswith('127.')): ifaces.append(iface) iface = ifaces[0] return iface
Example #5
Source File: config.py From FalconGate with GNU General Public License v3.0 | 6 votes |
def run(self): while 1: gws = netifaces.gateways() cgw = gws['default'][netifaces.AF_INET][0] if not homenet.gateway: homenet.gateway = cgw else: if homenet.gateway != cgw: utils.reconfigure_network(homenet.gateway, cgw) homenet.gateway = cgw try: with lock: utils.save_pkl_object(homenet, "homenet.pkl") except Exception as e: log.debug('FG-ERROR ' + str(e.__doc__) + " - " + str(e)) utils.reboot_appliance() else: pass time.sleep(10)
Example #6
Source File: view.py From cli with MIT License | 6 votes |
def best_remote_address(): """ Returns the "best" non-localback IP address for the local host, if possible. The "best" IP address is that bound to either the default gateway interface, if any, else the arbitrary first interface found. IPv4 is preferred, but IPv6 will be used if no IPv4 interfaces/addresses are available. """ default_gateway = net.gateways().get("default", {}) default_interface = default_gateway.get(net.AF_INET, (None, None))[1] \ or default_gateway.get(net.AF_INET6, (None, None))[1] \ or net.interfaces()[0] interface_addresses = net.ifaddresses(default_interface).get(net.AF_INET) \ or net.ifaddresses(default_interface).get(net.AF_INET6) \ or [] addresses = [ address["addr"] for address in interface_addresses if address.get("addr") ] return addresses[0] if addresses else None
Example #7
Source File: msf-autopwn.py From msf-autopwn with MIT License | 6 votes |
def get_iface(): ''' Gets the right interface for Responder ''' try: iface = netifaces.gateways()['default'][netifaces.AF_INET][1] except: ifaces = [] for iface in netifaces.interfaces(): # list of ipv4 addrinfo dicts ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, []) for entry in ipv4s: addr = entry.get('addr') if not addr: continue if not (iface.startswith('lo') or addr.startswith('127.')): ifaces.append(iface) iface = ifaces[0] return iface
Example #8
Source File: msf-autoshell.py From msf-autoshell with GNU General Public License v3.0 | 6 votes |
def get_iface(): ''' Grabs an interface so we can grab the IP off that interface ''' try: iface = netifaces.gateways()['default'][netifaces.AF_INET][1] except: ifaces = [] for iface in netifaces.interfaces(): # list of ipv4 addrinfo dicts ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, []) for entry in ipv4s: addr = entry.get('addr') if not addr: continue if not (iface.startswith('lo') or addr.startswith('127.')): ifaces.append(iface) # Just get the first interface iface = ifaces[0] return iface
Example #9
Source File: snappy.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def get_default_gateway_ip(): """Return the default gateway IP.""" gateways = netifaces.gateways() defaults = gateways.get("default") if not defaults: return def default_ip(family): gw_info = defaults.get(family) if not gw_info: return addresses = netifaces.ifaddresses(gw_info[1]).get(family) if addresses: return addresses[0]["addr"] return default_ip(netifaces.AF_INET) or default_ip(netifaces.AF_INET6)
Example #10
Source File: ipaddr.py From maas with GNU Affero General Public License v3.0 | 6 votes |
def get_machine_default_gateway_ip(): """Return the default gateway IP for the machine.""" gateways = netifaces.gateways() defaults = gateways.get("default") if not defaults: return def default_ip(family): gw_info = defaults.get(family) if not gw_info: return addresses = netifaces.ifaddresses(gw_info[1]).get(family) if addresses: return addresses[0]["addr"] return default_ip(netifaces.AF_INET) or default_ip(netifaces.AF_INET6)
Example #11
Source File: netutils.py From oslo.utils with Apache License 2.0 | 6 votes |
def _get_my_ipv4_address(): """Figure out the best ipv4 """ LOCALHOST = '127.0.0.1' gtw = netifaces.gateways() try: interface = gtw['default'][netifaces.AF_INET][1] except (KeyError, IndexError): LOG.info('Could not determine default network interface, ' 'using 127.0.0.1 for IPv4 address') return LOCALHOST try: return netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr'] except (KeyError, IndexError): LOG.info('Could not determine IPv4 address for interface %s, ' 'using 127.0.0.1', interface) except Exception as e: LOG.info('Could not determine IPv4 address for ' 'interface %(interface)s: %(error)s', {'interface': interface, 'error': e}) return LOCALHOST
Example #12
Source File: lib.py From pyp2p with MIT License | 6 votes |
def get_default_gateway(interface="default"): if sys.version_info < (3, 0, 0): if type(interface) == str: interface = unicode(interface) else: if type(interface) == bytes: interface = interface.decode("utf-8") if platform.system() == "Windows": if interface == "default": default_routes = [r for r in get_ipv4_routing_table() if r[0] == '0.0.0.0'] if default_routes: return default_routes[0][2] try: gws = netifaces.gateways() if sys.version_info < (3, 0, 0): return gws[interface][netifaces.AF_INET][0].decode("utf-8") else: return gws[interface][netifaces.AF_INET][0] except: # This can also mean the machine is directly accessible. return None
Example #13
Source File: nethelpers.py From voltha with Apache License 2.0 | 5 votes |
def _get_my_primary_interface(): gateways = ni.gateways() assert 'default' in gateways, \ ("No default gateway on host/container, " "cannot determine primary interface") default_gw_index = gateways['default'].keys()[0] # gateways[default_gw_index] has the format (example): # [('10.15.32.1', 'en0', True)] interface_name = gateways[default_gw_index][0][1] return interface_name
Example #14
Source File: address.py From netpwn with GNU General Public License v3.0 | 5 votes |
def address_info(): """Get networking information.""" print colored('Enter interface', 'green') interface = raw_input(colored('(netpwn: address_info) > ', 'red')) try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) val = struct.pack('256s', interface[:15]) info = fcntl.ioctl(sock.fileno(), 0x8927, val) joining = ['%02x' % ord(char) for char in info[18:24]] print colored('Your MAC is: ' + ':'.join(joining), 'green') except IOError as error: print colored('Invalid interface ' + str(error), 'yellow') sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(('8.8.8.8', 80)) print colored('Your ipv4 is : ' + (sock.getsockname()[0]), 'green') sock.close() try: addrs = netifaces.ifaddresses(interface) address6 = addrs[netifaces.AF_INET6][0]['addr'] address6_1 = addrs[netifaces.AF_INET6][1]['addr'] address6_2 = addrs[netifaces.AF_INET6][2]['addr'] print colored('Your ipv6 is: ' + address6, 'green') print colored('Your ipv6 is: ' + address6_1, 'green') print colored('Your ipv6 is: ' + address6_2, 'green') except ValueError as error: print colored('Invalid interface ' + str(error), 'yellow') my_gateway = netifaces.gateways() getgateway = my_gateway['default'][socket.AF_INET][0] print colored('Your default gateway is: ' + getgateway, 'green') my_ip = urlopen('http://ipinfo.io/ip').read() print colored('Your public IP is: ' + my_ip, 'green')
Example #15
Source File: optimization_algorithm_no_timelimit.py From Auto-PyTorch with Apache License 2.0 | 5 votes |
def get_default_network_interface_name(self): try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except: return 'lo'
Example #16
Source File: moose_router_check.py From malware-research with BSD 2-Clause "Simplified" License | 5 votes |
def get_default_gateway_windows(): """Use netifaces module to get the default gateway.""" try: import netifaces gws = netifaces.gateways() return gws['default'][netifaces.AF_INET][0] except: return None
Example #17
Source File: utils.py From zget with MIT License | 5 votes |
def default_interface(): """ Get default gateway interface. Some OSes return 127.0.0.1 when using socket.gethostbyname(socket.gethostname()), so we're attempting to get a kind of valid hostname here. """ try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except KeyError: # Sometimes 'default' is empty but AF_INET exists alongside it return netifaces.gateways()[netifaces.AF_INET][0][1]
Example #18
Source File: helper.py From photoframe with GNU General Public License v3.0 | 5 votes |
def getDeviceIp(): try: import netifaces if 'default' in netifaces.gateways() and netifaces.AF_INET in netifaces.gateways()['default']: dev = netifaces.gateways()['default'][netifaces.AF_INET][1] if netifaces.ifaddresses(dev) and netifaces.AF_INET in netifaces.ifaddresses(dev): net = netifaces.ifaddresses(dev)[netifaces.AF_INET] if len(net) > 0 and 'addr' in net[0]: return net[0]['addr'] except ImportError: logging.error('User has not installed python-netifaces, using checkNetwork() instead (depends on internet)') return helper._checkNetwork() except: logging.exception('netifaces call failed, using checkNetwork() instead (depends on internet)') return helper._checkNetwork()
Example #19
Source File: utils.py From evillimiter with MIT License | 5 votes |
def get_default_interface(): """ Returns the default IPv4 interface """ gateways = netifaces.gateways() if 'default' in gateways and netifaces.AF_INET in gateways['default']: return gateways['default'][netifaces.AF_INET][1]
Example #20
Source File: utils.py From evillimiter with MIT License | 5 votes |
def get_default_gateway(): """ Returns the default IPv4 gateway address """ gateways = netifaces.gateways() if 'default' in gateways and netifaces.AF_INET in gateways['default']: return gateways['default'][netifaces.AF_INET][0]
Example #21
Source File: _utils.py From shade with Apache License 2.0 | 5 votes |
def localhost_supports_ipv6(): """Determine whether the local host supports IPv6 We look for a default route that supports the IPv6 address family, and assume that if it is present, this host has globally routable IPv6 connectivity. """ try: return netifaces.AF_INET6 in netifaces.gateways()['default'] except AttributeError: return False
Example #22
Source File: optimization_algorithm.py From Auto-PyTorch with Apache License 2.0 | 5 votes |
def get_default_network_interface_name(self): """Get the default network interface name Returns: str -- The default network interface name """ try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except: return 'lo'
Example #23
Source File: sonota.py From SonOTA with GNU General Public License v2.0 | 5 votes |
def defaultinterface(): '''The interface the default gateway is on, if there is one.''' try: return netifaces.gateways()['default'][netifaces.AF_INET][1] except: return None
Example #24
Source File: utils.py From esdc-ce with Apache License 2.0 | 5 votes |
def _get_local_netinfo(iface): ifconfig = netifaces.ifaddresses(iface)[netifaces.AF_INET][0] ifconfig['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0] ip = ipaddress.ip_interface(u'%s/%s' % (ifconfig['addr'], ifconfig['netmask'])) ifconfig['network'] = str(ip.network.network_address) ifconfig['iface'] = iface return ifconfig
Example #25
Source File: utils.py From esdc-ce with Apache License 2.0 | 5 votes |
def get_local_netinfo(iface=None): if not iface: try: iface = netifaces.gateways()['default'][netifaces.AF_INET][1] except (KeyError, IndexError): raise OSError('Main network interface was not found') if iface not in netifaces.interfaces(): raise ValueError('Network interface "%s" is not available on this system' % iface) try: return _get_local_netinfo(iface) except (KeyError, IndexError): raise OSError('Network information for interface "%s" is not available' % iface)
Example #26
Source File: views.py From upribox with GNU General Public License v3.0 | 5 votes |
def get_entries(): gateway = None try: gateway = ni.gateways()['default'][AF_INET][0] except KeyError: pass return sorted( DeviceEntry.objects.filter(last_seen__gte=datetime.now() - timedelta(weeks=1), mac__regex=r'([0-9a-f]:?){12}') .exclude(ip=gateway), key=lambda x: get_device_name(x).upper() )
Example #27
Source File: advertise.py From touchosc2midi with MIT License | 5 votes |
def default_route_interface(): """ Query netifaces for the default route's ip. Note: this only checks for IPv4 addresses. """ interface = netifaces.gateways()['default'] if interface: name = interface[netifaces.AF_INET][1] ip = netifaces.ifaddresses(name)[netifaces.AF_INET][0]['addr'] log.debug("found '{}:{}' as default route.".format(name, ip)) return ip else: raise RuntimeError("default interface not found. Check your network or use --ip switch.")
Example #28
Source File: TestHelper.py From nmos-testing with Apache License 2.0 | 5 votes |
def get_default_ip(): """Get this machine's preferred IPv4 address""" if CONFIG.BIND_INTERFACE is None: default_gw = netifaces.gateways()['default'] if netifaces.AF_INET in default_gw: preferred_interface = default_gw[netifaces.AF_INET][1] else: interfaces = netifaces.interfaces() preferred_interface = next((i for i in interfaces if i != 'lo'), interfaces[0]) else: preferred_interface = CONFIG.BIND_INTERFACE return netifaces.ifaddresses(preferred_interface)[netifaces.AF_INET][0]['addr']
Example #29
Source File: lib.py From pyp2p with MIT License | 5 votes |
def get_lan_ip(interface="default"): if sys.version_info < (3, 0, 0): if type(interface) == str: interface = unicode(interface) else: if type(interface) == bytes: interface = interface.decode("utf-8") # Get ID of interface that handles WAN stuff. default_gateway = get_default_gateway(interface) gateways = netifaces.gateways() wan_id = None if netifaces.AF_INET in gateways: gw_list = gateways[netifaces.AF_INET] for gw_info in gw_list: if gw_info[0] == default_gateway: wan_id = gw_info[1] break # Find LAN IP of interface for WAN stuff. interfaces = netifaces.interfaces() if wan_id in interfaces: families = netifaces.ifaddresses(wan_id) if netifaces.AF_INET in families: if_info_list = families[netifaces.AF_INET] for if_info in if_info_list: if "addr" in if_info: return if_info["addr"] """ Execution may reach here if the host is using virtual interfaces on Linux and there are no gateways which suggests the host is a VPS or server. In this case """ if platform.system() == "Linux": if ip is not None: return ip.routes["8.8.8.8"]["prefsrc"] return None
Example #30
Source File: nat_pmp.py From pyp2p with MIT License | 5 votes |
def get_gateway_addr(): """Use netifaces to get the gateway address, if we can't import it then fall back to a hack to obtain the current gateway automatically, since Python has no interface to sysctl(). This may or may not be the gateway we should be contacting. It does not guarantee correct results. This function requires the presence of netstat on the path on POSIX and NT. """ try: import netifaces return netifaces.gateways()["default"][netifaces.AF_INET][0] except ImportError: shell_command = 'netstat -rn' if os.name == "posix": pattern = \ re.compile('(?:default|0\.0\.0\.0|::/0)\s+([\w\.:]+)\s+.*UG') elif os.name == "nt": if platform.version().startswith("6.1"): pattern = re.compile(".*?0.0.0.0[ ]+0.0.0.0[ ]+(.*?)[ ]+?.*?\n") else: pattern = re.compile(".*?Default Gateway:[ ]+(.*?)\n") system_out = os.popen(shell_command, 'r').read() if not system_out: raise NATPMPNetworkError(NATPMP_GATEWAY_CANNOT_FIND, error_str(NATPMP_GATEWAY_CANNOT_FIND)) match = pattern.search(system_out) if not match: raise NATPMPNetworkError(NATPMP_GATEWAY_CANNOT_FIND, error_str(NATPMP_GATEWAY_CANNOT_FIND)) addr = match.groups()[0].strip() return addr