Python netifaces.AF_INET Examples
The following are 30
code examples of netifaces.AF_INET().
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: topology.py From InsightAgent with Apache License 2.0 | 7 votes |
def get_interfaces(): interfaces = netifaces.interfaces() interfaces.remove('lo') out_interfaces = dict() for interface in interfaces: addrs = netifaces.ifaddresses(interface) out_addrs = dict() if netifaces.AF_INET in addrs.keys(): out_addrs["ipv4"] = addrs[netifaces.AF_INET] if netifaces.AF_INET6 in addrs.keys(): out_addrs["ipv6"] = addrs[netifaces.AF_INET6] out_interfaces[interface] = out_addrs return out_interfaces
Example #2
Source File: multicast_checks.py From rift-python with Apache License 2.0 | 7 votes |
def _create_ipv4_sockets(loopback_enabled): # Open a multicast send socket, with IP_MULTICAST_LOOP enabled or disabled as requested. mcast_address = "224.0.1.195" port = 49501 group = (mcast_address, port) txsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) txsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if loopback_enabled: txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) else: txsock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0) txsock.connect(group) # Open a multicast receive socket and join the group rxsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) req = struct.pack("=4sl", socket.inet_aton(mcast_address), socket.INADDR_ANY) rxsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, req) rxsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) rxsock.bind(group) return (txsock, rxsock)
Example #3
Source File: _net.py From flocker with Apache License 2.0 | 7 votes |
def get_all_ips(): """ Find all IPs for this machine. :return: ``set`` of IP addresses (``IPAddress``). """ ips = set() interfaces = netifaces.interfaces() for interface in interfaces: addresses = netifaces.ifaddresses(interface) for address_family in (netifaces.AF_INET, netifaces.AF_INET6): family_addresses = addresses.get(address_family) if not family_addresses: continue for address in family_addresses: ips.add(ipaddress_from_string(address['addr'])) return ips
Example #4
Source File: net.py From pykit with MIT License | 7 votes |
def get_host_devices(iface_prefix=''): rst = {} for ifacename in netifaces.interfaces(): if not ifacename.startswith(iface_prefix): continue addrs = netifaces.ifaddresses(ifacename) if netifaces.AF_INET in addrs and netifaces.AF_LINK in addrs: ips = [addr['addr'] for addr in addrs[netifaces.AF_INET]] for ip in ips: if is_ip4_loopback(ip): break else: rst[ifacename] = {'INET': addrs[netifaces.AF_INET], 'LINK': addrs[netifaces.AF_LINK]} return rst
Example #5
Source File: network.py From Paradrop with Apache License 2.0 | 6 votes |
def select_chute_subnet_pool(host_config): """ Select IP subnet to use as pool for chutes. Behavior depends on whether a static subnet is configured or auto configuration is requested. If the chuteSubnetPool option is set to 'auto', then we check the WAN interface address and choose either 10.128.0.0/9 or 192.168.128.0/17 to avoid conflict. Otherwise, we used the specified subnet. """ pool = datastruct.getValue(host_config, "system.chuteSubnetPool", 'auto') wan_ifname = datastruct.getValue(host_config, 'wan.interface', 'eth0') if pool == 'auto': addresses = netifaces.ifaddresses(wan_ifname) ipv4_addrs = addresses.get(netifaces.AF_INET, []) if any(x['addr'].startswith("10.") for x in ipv4_addrs): return "192.168.128.0/17" else: return "10.128.0.0/9" else: return pool
Example #6
Source File: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 6 votes |
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: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 6 votes |
def connectRemotes(self): for remote in self.remoteAddrs: if remote['socket']: continue # Attempt reconnection at most once every N seconds if remote['connectFailure'] and remote['connectFailure'] > time.time()-self.remoteRetry: return remoteConnection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) remoteConnection.setblocking(0) self.logger.info('REMOTE: Connecting to remote %s' % remote['addr']) remote['connecting'] = True try: remoteConnection.connect((remote['addr'], self.remotePort)) except socket.error as e: if e.errno == errno.EINPROGRESS: remote['socket'] = remoteConnection else: remote['connecting'] = False remote['connectFailure'] = time.time()
Example #8
Source File: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 6 votes |
def addListener(self, addr, port, service): if self.isBroadcast(addr): self.etherAddrs[addr] = self.broadcastIpToMac(addr) elif self.isMulticast(addr): self.etherAddrs[addr] = self.multicastIpToMac(addr) else: # unicast -- we don't know yet which IP we'll want to send to self.etherAddrs[addr] = None # Set up the receiving socket and corresponding IP and interface information. # One receiving socket is required per multicast address. rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) for interface in self.interfaces: (ifname, mac, ip, netmask) = self.getInterface(interface) # Add this interface to the receiving socket's list. if self.isBroadcast(addr): rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) elif self.isMulticast(addr): packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip)) rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress) # Generate a transmitter socket. Each interface # requires its own transmitting socket. if interface not in self.noTransmitInterfaces: tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) tx.bind((ifname, 0)) self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service}) rx.bind((addr, port)) self.receivers.append(rx)
Example #9
Source File: engine.py From rift-python with Apache License 2.0 | 6 votes |
def default_physical_interface(self): # When simulated interfaces are disabled, the interface names on nodes correspond to real # interfaces on the host platform. # When simulated interface are enabled, the interface names on nodes are "fake" i.e. they do # not correspond to real interfaces on the host platform. All these simulated interfaces # actually run on a single real interface, referred to as the physical interface. Traffic to # and from different simulated interfaces are distinguished by using different multicast # addresses and port numbers for each simulated interface. # Pick the first interface with a broadcast IPv4 address (if any) as the default. for intf_name in netifaces.interfaces(): addresses = netifaces.ifaddresses(intf_name) if netifaces.AF_INET in addresses: ipv4_addresses = addresses[netifaces.AF_INET] for ipv4_address in ipv4_addresses: if 'broadcast' in ipv4_address: return intf_name print("Cannot pick default physical interface: no broadcast interface found") sys.exit(1)
Example #10
Source File: network.py From pulseaudio-dlna with GNU General Public License v3.0 | 6 votes |
def __pyroute2_get_host_by_ip(ip): import pyroute2 ipr = pyroute2.IPRoute() routes = ipr.get_routes(family=socket.AF_INET, dst=ip) ipr.close() for route in routes: for attr in route.get('attrs', []): if type(attr) is list: if attr[0] == 'RTA_PREFSRC': return attr[1] else: if attr.cell[0] == 'RTA_PREFSRC': return attr.get_value() logger.critical( '__pyroute2_get_host_by_ip() - No host found for IP {}!'.format(ip)) return None
Example #11
Source File: nat.py From pyquarkchain with MIT License | 6 votes |
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str: """ For a given UPnP device, return the internal IP address of this host machine that can be used for a NAT mapping. """ parsed_url = urlparse(upnp_dev.location) # Get an ipaddress.IPv4Network instance for the upnp device's network. upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False) for iface in netifaces.interfaces(): for family, addresses in netifaces.ifaddresses(iface).items(): # TODO: Support IPv6 addresses as well. if family != netifaces.AF_INET: continue for item in addresses: if ipaddress.ip_address(item["addr"]) in upnp_dev_net: return item["addr"] raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname)
Example #12
Source File: utils_net.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
def get_netmask(self): """ Get ip network netmask """ if not CTYPES_SUPPORT: raise exceptions.TestSkipError("Getting the netmask requires " "python > 2.4") ifreq = struct.pack('16sH14s', self.name.encode(), socket.AF_INET, b'\x00' * 14) try: res = fcntl.ioctl(sockfd, arch.SIOCGIFNETMASK, ifreq) except IOError: return 0 netmask = socket.ntohl(struct.unpack('16sH2xI8x', res)[2]) return 32 - int(math.log(ctypes.c_uint32(~netmask).value + 1, 2))
Example #13
Source File: utils_net.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
def canonicalize(self, ip_str): """ Parse an IP string for listen to IPAddress content. """ try: if ':' in ip_str: self.version = 'ipv6' if '%' in ip_str: ip_str, scope = ip_str.split('%') self.scope = int(scope) self.packed_addr = socket.inet_pton(socket.AF_INET6, ip_str) self.addr = socket.inet_ntop(socket.AF_INET6, self.packed_addr) else: self.version = 'ipv4' self.packed_addr = socket.inet_pton(socket.AF_INET, ip_str) self.addr = socket.inet_ntop(socket.AF_INET, self.packed_addr) except socket.error as detail: if 'illegal IP address' in str(detail): self.addr = ip_str self.version = 'hostname'
Example #14
Source File: wol.py From epoptes with GNU General Public License v3.0 | 6 votes |
def get_broadcast_list(): """Return all broadcast addresses. E.g. WOL messages need to be sent from all NICs. """ brlist = ['<broadcast>'] ifaces = [iface for iface in netifaces.interfaces() if iface != 'lo'] for ifname in ifaces: # An interface can have more than one address, even within the # same family (AF_INET), or none, so check this case too. addresses = netifaces.ifaddresses(ifname) if netifaces.AF_INET not in addresses: continue for addr in addresses[netifaces.AF_INET]: if 'broadcast' in addr: brlist.append(addr['broadcast']) return brlist
Example #15
Source File: wol.py From epoptes with GNU General Public License v3.0 | 6 votes |
def wake_on_lan(macaddress): """Power on remote computers using Wake On LAN.""" # Handle MACs with or without separators. if len(macaddress) == 12: pass elif len(macaddress) == 12 + 5: sep = macaddress[2] macaddress = macaddress.replace(sep, '') else: raise ValueError('Incorrect MAC address format') print("Sending magic packet to", macaddress) packet = bytes.fromhex(''.join(['FFFFFFFFFFFF', macaddress * 20])) # Broadcast it to the LAN. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) for brd in get_broadcast_list(): sock.sendto(packet, (brd, 9))
Example #16
Source File: util.py From apple_bleee with GNU General Public License v3.0 | 6 votes |
def get_ip_for_interface(interface_name, ipv6=False): """ Get the ip address in IPv4 or IPv6 for a specific network interface :param str interace_name: declares the network interface name for which the ip should be accessed :param bool ipv6: Boolean indicating if the ipv6 address should be rertrieved :return: (str ipaddress, byte ipaddress_bytes) returns a tuple with the ip address as a string and in bytes """ addresses = netifaces.ifaddresses(interface_name) if netifaces.AF_INET6 in addresses and ipv6: # Use the normal ipv6 address addr = addresses[netifaces.AF_INET6][0]['addr'].split('%')[0] bytes_addr = ipaddress.IPv6Address(addr).packed elif netifaces.AF_INET in addresses and not ipv6: addr = addresses[netifaces.AF_INET][0]['addr'] bytes_addr = socket.inet_aton(addr) else: addr = None bytes_addr = None return addr, bytes_addr
Example #17
Source File: localif.py From pscheduler with Apache License 2.0 | 6 votes |
def __init__(self, data # Data suitable for this class ): valid, message = data_is_valid(data) if not valid: raise ValueError("Invalid data: %s" % message) self.cidrs = [] for iface in netifaces.interfaces(): ifaddrs = netifaces.ifaddresses(iface) if netifaces.AF_INET in ifaddrs: for ifaddr in ifaddrs[netifaces.AF_INET]: if 'addr' in ifaddr: self.cidrs.append(ipaddress.ip_network(unicode(ifaddr['addr']))) if netifaces.AF_INET6 in ifaddrs: for ifaddr in ifaddrs[netifaces.AF_INET6]: if 'addr' in ifaddr: #add v6 but remove stuff like %eth0 that gets thrown on end of some addrs self.cidrs.append(ipaddress.ip_network(unicode(ifaddr['addr'].split('%')[0])))
Example #18
Source File: network.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 5 votes |
def update(self): for iface, newio in psutil.net_io_counters(True).items(): if not iface.startswith('lo'): netinfo = netifaces.ifaddresses(iface) if netinfo.get(netifaces.AF_INET) and not self._is_ignored(iface): newio = self._net_io_counters(newio) newio['iface'] = iface newio.update(netinfo[netifaces.AF_INET][0]) self._deltas(self.nics.get(iface,{}), newio) self.nics[iface] = newio elif iface in self.nics: del self.nics[iface] self.data['nics'] = sorted(self.nics.values(), key=lambda n:n['iface']) self.data['total'] = self._deltas(self.data.get('total',{}), self._net_io_counters()) super(Plugin, self).update()
Example #19
Source File: worker.py From SecPi with GNU General Public License v3.0 | 5 votes |
def get_ip_addresses(self): result = [] for interface in netifaces.interfaces(): # interate through interfaces: eth0, eth1, wlan0... if (interface != "lo") and (netifaces.AF_INET in netifaces.ifaddresses(interface)): # filter loopback, and active ipv4 for ip_address in netifaces.ifaddresses(interface)[netifaces.AF_INET]: logging.debug("Adding %s IP to result" % ip_address['addr']) result.append(ip_address['addr']) if (interface != "lo") and (netifaces.AF_INET6 in netifaces.ifaddresses(interface)): # filter loopback, and active ipv6 for ipv6_address in netifaces.ifaddresses(interface)[netifaces.AF_INET6]: logging.debug("Adding %s IP to result" % ipv6_address['addr']) result.append(ipv6_address['addr']) return result # function which requests the initial config from the manager
Example #20
Source File: misphere.py From pysphere with MIT License | 5 votes |
def init(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.socket.connect((self.ms_ip, self.ms_tcp_port)) self.socket_1 = socket.socket() self.recv_handle_live = True self.recv_thread = threading.Thread(target=self.recv_handler) self.recv_thread.daemon = True self.session = Session() self.session.conf = {} self.session.locks = {} self.last_send = 0
Example #21
Source File: misphere.py From pysphere with MIT License | 5 votes |
def register_tcp(self, params={}): for e in ni.interfaces(): if e.lower().startswith('w'): ip = ni.ifaddresses(e)[ni.AF_INET][0]['addr'] if ip.startswith("192.168.42."): break params = {"param": ip, "type": "TCP"} self.send(REGISTER_TCP, params) return self.recv()
Example #22
Source File: devices.py From Paradrop with Apache License 2.0 | 5 votes |
def select_brlan_address(hostConfig): """ Select IP address and netmask to use for LAN bridge. Behavior depends on the proto field, which can either be 'auto' or 'static'. When proto is set to 'auto', we check the WAN interface address and choose either 10.0.0.0 or 192.168.0.1 to avoid conflict. Otherwise, when proto is set to 'static', we use the specified address. """ proto = datastruct.getValue(hostConfig, 'lan.proto', 'auto') netmask = datastruct.getValue(hostConfig, 'lan.netmask', '255.255.255.0') wan_ifname = datastruct.getValue(hostConfig, 'wan.interface', 'eth0') if proto == 'auto': addresses = netifaces.ifaddresses(wan_ifname) ipv4_addrs = addresses.get(netifaces.AF_INET, []) if any(x['addr'].startswith("10.") for x in ipv4_addrs): return "192.168.0.1", netmask else: return "10.0.0.1", netmask else: return hostConfig['lan']['ipaddr'], netmask # # Chute update functions #
Example #23
Source File: test_devices.py From Paradrop with Apache License 2.0 | 5 votes |
def test_select_brlan_address(ifaddresses): host_config = { 'wan': { 'interface': 'eth0' }, 'lan': { 'proto': 'auto' } } # Mock ifaddresses as if WAN interface has 192.x.x.x address. ifaddrs = { netifaces.AF_INET: [ { 'addr': '192.168.1.20' } ] } ifaddresses.return_value = ifaddrs addr, netmask = devices.select_brlan_address(host_config) assert addr.startswith("10.") # Mock ifaddresses as if WAN interface has 10.x.x.x address. ifaddrs[netifaces.AF_INET] = [{ 'addr': '10.42.0.20' }] addr, netmask = devices.select_brlan_address(host_config) assert addr.startswith("192.168.") # Test static assignment. host_config['lan']['proto'] = 'static' host_config['lan']['ipaddr'] = '192.168.1.1' host_config['lan']['netmask'] = '255.255.255.0' addr, netmask = devices.select_brlan_address(host_config) assert addr == '192.168.1.1' assert netmask == '255.255.255.0'
Example #24
Source File: test_network.py From Paradrop with Apache License 2.0 | 5 votes |
def test_select_chute_subnet_pool(ifaddresses): host_config = { 'wan': { 'interface': 'eth0' }, 'system': { 'chuteSubnetPool': 'auto' } } # Mock ifaddresses as if WAN interface has 192.x.x.x address. ifaddrs = { netifaces.AF_INET: [ { 'addr': '192.168.1.20' } ] } ifaddresses.return_value = ifaddrs pool = network.select_chute_subnet_pool(host_config) assert pool.startswith("10.") # Mock ifaddresses as if WAN interface has 10.x.x.x address. ifaddrs[netifaces.AF_INET] = [{ 'addr': '10.42.0.20' }] pool = network.select_chute_subnet_pool(host_config) assert pool.startswith("192.168.") # Test static assignment. host_config['system']['chuteSubnetPool'] = '192.168.128.0/17' pool = network.select_chute_subnet_pool(host_config) assert pool == '192.168.128.0/17'
Example #25
Source File: network.py From pyspectator with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __get_active_ip_address(cls): ip_address = None s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('8.8.8.8', 80)) ip_address = s.getsockname()[0] except: s.close() return ip_address
Example #26
Source File: multicast-relay.py From multicast-relay with GNU General Public License v3.0 | 5 votes |
def __init__(self, homebrewNetifaces, ifNameStructLen): self.homebrewNetifaces = homebrewNetifaces self.ifNameStructLen = ifNameStructLen if self.homebrewNetifaces: Netifaces.AF_LINK = 1 Netifaces.AF_INET = 2 self.interfaceAttrs = {} else: import netifaces Netifaces.AF_LINK = netifaces.AF_LINK Netifaces.AF_INET = netifaces.AF_INET
Example #27
Source File: multicast_checks.py From rift-python with Apache License 2.0 | 5 votes |
def find_ethernet_interface(): for intf_name in netifaces.interfaces(): addresses = netifaces.ifaddresses(intf_name) if netifaces.AF_INET in addresses: ipv4_addresses = addresses[netifaces.AF_INET] for ipv4_address in ipv4_addresses: if 'broadcast' in ipv4_address: return intf_name assert False, "Cannot find ethernet interface to perform loopback test" return None
Example #28
Source File: utils.py From rift-python with Apache License 2.0 | 5 votes |
def interface_ipv4_address(interface_name): interface_addresses = netifaces.interfaces() if not interface_name in netifaces.interfaces(): return None interface_addresses = netifaces.ifaddresses(interface_name) if not netifaces.AF_INET in interface_addresses: return None return interface_addresses[netifaces.AF_INET][0]['addr']
Example #29
Source File: utils.py From rift-python with Apache License 2.0 | 5 votes |
def is_valid_ipv4_address(address): try: socket.inet_pton(socket.AF_INET, address) except socket.error: return False return True
Example #30
Source File: network.py From pulseaudio-dlna with GNU General Public License v3.0 | 5 votes |
def default_ipv4(): try: default_if = netifaces.gateways()['default'][netifaces.AF_INET][1] return netifaces.ifaddresses(default_if)[netifaces.AF_INET][0]['addr'] except: traceback.print_exc() return None