Python netifaces.AF_LINK Examples
The following are 27
code examples of netifaces.AF_LINK().
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: 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 #2
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 #3
Source File: pcapdnet.py From arissploit with GNU General Public License v3.0 | 6 votes |
def get_if_raw_hwaddr(iff): err = create_string_buffer(PCAP_ERRBUF_SIZE) devs = POINTER(pcap_if_t)() ret = b"\0\0\0\0\0\0" if pcap_findalldevs(byref(devs), err) < 0: return ret try: p = devs while p: if p.contents.name.endswith(iff.encode('ascii')): a = p.contents.addresses while a: if hasattr(socket, 'AF_LINK') and a.contents.addr.contents.sa_family == socket.AF_LINK: ap = a.contents.addr val = cast(ap, POINTER(sockaddr_dl)) ret = bytes(val.contents.sdl_data[ val.contents.sdl_nlen : val.contents.sdl_nlen + val.contents.sdl_alen ]) a = a.contents.next break p = p.contents.next return ret finally: pcap_freealldevs(devs)
Example #4
Source File: pcapdnet.py From kamene with GNU General Public License v2.0 | 6 votes |
def get_if_raw_hwaddr(iff): err = create_string_buffer(PCAP_ERRBUF_SIZE) devs = POINTER(pcap_if_t)() ret = b"\0\0\0\0\0\0" if pcap_findalldevs(byref(devs), err) < 0: return ret try: p = devs while p: if p.contents.name.endswith(iff.encode('ascii')): a = p.contents.addresses while a: if hasattr(socket, 'AF_LINK') and a.contents.addr.contents.sa_family == socket.AF_LINK: ap = a.contents.addr val = cast(ap, POINTER(sockaddr_dl)) ret = bytes(val.contents.sdl_data[ val.contents.sdl_nlen : val.contents.sdl_nlen + val.contents.sdl_alen ]) a = a.contents.next break p = p.contents.next return ret finally: pcap_freealldevs(devs)
Example #5
Source File: GEventNetworkManager.py From OpenMTC with Eclipse Public License 1.0 | 6 votes |
def _get_addresses_from_ifaddresses(self, ifaddresses): """Get addresses of a given interface :param ifaddresses: raw addresses of interface (from netifaces) :return: list of addresses """ addresses = [] for family in ifaddresses: if family != netifaces.AF_LINK: # no hwaddr for addr in ifaddresses[family]: a = addr["addr"] if family == netifaces.AF_INET6: a = self._remove_ipv6_special_stuff(a) addresses.append( Address(address=a, family=family)) return addresses
Example #6
Source File: GEventNetworkManager.py From OpenMTC with Eclipse Public License 1.0 | 6 votes |
def _create_interface(self, name, ifaddresses): """Create Interface tuple based on given interfaces addresses. (function independent of netifaces) :param name: :param ifaddresses: :return: """ addresses = self._get_addresses_from_ifaddresses(ifaddresses) try: hwaddress = ifaddresses[netifaces.AF_LINK][0]["addr"] except (IndexError, KeyError): self.logger.debug("No hardware address found for %s!", name) hwaddress = None return Interface(name=name, addresses=addresses, hwaddress=hwaddress)
Example #7
Source File: GEventNetworkManager.py From OpenMTC with Eclipse Public License 1.0 | 6 votes |
def _get_interface(self, name): """Returns an Interface object identified by name :param name: name of interface :return Interface: interface :raise UnknownInterface: if interface was not found """ if name not in netifaces.interfaces(): raise InterfaceNotFoundException("%s was not found" % name) else: ifaddresses = netifaces.ifaddresses(name) addresses = self._get_addresses_from_ifaddresses(ifaddresses) try: hwaddress = ifaddresses[netifaces.AF_LINK][0]["addr"] except (IndexError, KeyError): self.logger.debug("No hardware address found for %s!", name) hwaddress = None return Interface(name=name, addresses=addresses, hwaddress=hwaddress)
Example #8
Source File: network_services.py From expressvpn_leak_testing with MIT License | 6 votes |
def interface(self): # TODO: Reject this idea? Maybe interfaces should be chosen without # regard to connection status, if NM can't be trusted. # In which case, tests that get a list of interfaces should just use # netifaces directly. try: return self._settings['connection']['interface-name'] except KeyError: connection_type = self._settings['connection']['type'] # TODO: Test this on different types. mac_address = self._settings[connection_type]['mac-address'] for iface in netifaces.interfaces(): iface_mac = netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'].lower() if mac_address.lower() == iface_mac: return iface raise XVEx("Couldn't find any connection interfaces")
Example #9
Source File: test_dhcp.py From cloudbase-init with Apache License 2.0 | 5 votes |
def test_get_mac_address_by_local_ip(self, mock_interfaces, mock_ifaddresses): fake_addresses = {} fake_addresses[netifaces.AF_INET] = [{'addr': 'fake address'}] fake_addresses[netifaces.AF_LINK] = [{'addr': 'fake mac'}] mock_interfaces.return_value = ['fake interface'] mock_ifaddresses.return_value = fake_addresses response = dhcp._get_mac_address_by_local_ip('fake address') mock_interfaces.assert_called_once_with() mock_ifaddresses.assert_called_once_with('fake interface') self.assertEqual(fake_addresses[netifaces.AF_LINK][0]['addr'], response)
Example #10
Source File: PAS5211_comm.py From voltha with Apache License 2.0 | 5 votes |
def determine_src_mac(iface): if iface in netifaces.interfaces(): return netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'] return None
Example #11
Source File: pcapdnet.py From arissploit with GNU General Public License v3.0 | 5 votes |
def get_if_raw_hwaddr(iff): if iff == scapy.arch.LOOPBACK_NAME: return (772, '\x00'*6) try: s = netifaces.ifaddresses(iff)[netifaces.AF_LINK][0]['addr'] return struct.pack('BBBBBB', *[ int(i, 16) for i in s.split(':') ]) except: raise Scapy_Exception("Error in attempting to get hw address for interface [%s]" % iff) return l
Example #12
Source File: pcapdnet.py From kamene with GNU General Public License v2.0 | 5 votes |
def get_if_raw_hwaddr(iff): if iff == kamene.arch.LOOPBACK_NAME: return (772, '\x00'*6) try: s = netifaces.ifaddresses(iff)[netifaces.AF_LINK][0]['addr'] return struct.pack('BBBBBB', *[ int(i, 16) for i in s.split(':') ]) except: raise Kamene_Exception("Error in attempting to get hw address for interface [%s]" % iff) return l
Example #13
Source File: network.py From landscape-client with GNU General Public License v2.0 | 5 votes |
def get_mac_address(ifaddresses): """ Return the hardware MAC address for an interface in human friendly form, ie. six colon separated groups of two hexadecimal digits, if available; otherwise an empty string. @param ifaddresses: a dict as returned by L{netifaces.ifaddresses} or the address data in L{get_active_interfaces}'s output. """ if netifaces.AF_LINK in ifaddresses: return ifaddresses[netifaces.AF_LINK][0].get('addr', '') return ''
Example #14
Source File: network.py From landscape-client with GNU General Public License v2.0 | 5 votes |
def get_active_interfaces(): """Generator yields (active network interface name, address data) tuples. Address data is formatted exactly like L{netifaces.ifaddresses}, e.g.:: ('eth0', { AF_LINK: [ {'addr': '...', 'broadcast': '...'}, ], AF_INET: [ {'addr': '...', 'broadcast': '...', 'netmask': '...'}, {'addr': '...', 'broadcast': '...', 'netmask': '...'}, ...], AF_INET6: [ {'addr': '...', 'netmask': '...'}, {'addr': '...', 'netmask': '...'}, ...], }) Interfaces with no IP address are ignored. """ for interface in netifaces.interfaces(): ifaddresses = netifaces.ifaddresses(interface) # Skip interfaces with no IPv4 or IPv6 addresses. inet_addr = ifaddresses.get(netifaces.AF_INET, [{}])[0].get('addr') inet6_addr = ifaddresses.get(netifaces.AF_INET6, [{}])[0].get('addr') if inet_addr or inet6_addr: yield interface, ifaddresses
Example #15
Source File: Status.py From tipi with GNU General Public License v3.0 | 5 votes |
def __init__(self): self.__records = [] for name in netifaces.interfaces(): if not name.startswith("lo"): iface = netifaces.ifaddresses(name) if netifaces.AF_LINK in iface: self.__records.append( "MAC_{}={}".format( str(name).upper(), iface[netifaces.AF_LINK][0]["addr"] ) ) if netifaces.AF_INET in iface: self.__records.append( "IP_{}={}".format( str(name).upper(), iface[netifaces.AF_INET][0]["addr"] ) ) with open("/home/tipi/tipi/version.txt", "r") as fh_in: for line in fh_in.readlines(): parts = line.split("=") self.__records.append( "{}={}".format(str(parts[0]).strip().upper(), str(parts[1]).strip()) ) with open("/home/tipi/tipi.uuid", "r") as fh_in: self.__records.append("UUID={}".format(fh_in.readline().strip())) # This needs to work even if there is no network.. thus a catch all. try: upgradeCheck = str(check_output(["/home/tipi/tipi/setup/upgrade.sh"]), 'ascii') latest = upgradeCheck.split("\n")[1] if latest.startswith("Latest Version: "): gitver=latest.split(":")[1].strip() self.__records.append(f'LATEST={gitver}') except Exception as e: logger.warn("failed to fetch latest version info")
Example #16
Source File: sdnpwn_common.py From sdnpwn with MIT License | 5 votes |
def getMacAddress(iface): if(iface in netifaces.interfaces()): return netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'] else: return '0'
Example #17
Source File: test_ngs_basic_ops.py From networking-generic-switch with Apache License 2.0 | 5 votes |
def get_local_port_mac(self, bridge_name): mac_address = netifaces.ifaddresses( bridge_name)[netifaces.AF_LINK][0].get('addr') return mac_address
Example #18
Source File: wificommon.py From pywificontrol with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_device_mac(self): try: return ifaddresses(self.interface)[AF_LINK][0]['addr'] except KeyError: return "00:00:00:00:00:00"
Example #19
Source File: base.py From raw-packet with MIT License | 5 votes |
def get_interface_mac_address(self, interface_name: str = 'eth0', exit_on_failure: bool = True, exit_code: int = 7, quiet: bool = False) -> Union[None, str]: """ Get MAC address of the network interface :param interface_name: Network interface name (default: 'eth0') :param exit_on_failure: Exit in case of error (default: True) :param exit_code: Set exit code integer (default: 7) :param quiet: Quiet mode, if True no console output (default: False) :return: MAC address string (example: '01:23:45:67:89:0a') or None in case of error """ if interface_name in self._network_interfaces_settings.keys(): if self._network_interfaces_settings[interface_name]['mac-address'] is not None: return self._network_interfaces_settings[interface_name]['mac-address'] try: return str(ifaddresses(interface_name)[AF_LINK][0]['addr']) except NameError: return get_mac_address(interface=interface_name) except ValueError: pass except KeyError: pass if not quiet: self.print_error('Network interface: ', interface_name, ' does not have MAC address!') if exit_on_failure: exit(exit_code) return None
Example #20
Source File: dhcp.py From cloudbase-init with Apache License 2.0 | 5 votes |
def _get_mac_address_by_local_ip(ip_addr): for iface in netifaces.interfaces(): addrs = netifaces.ifaddresses(iface) for addr in addrs.get(netifaces.AF_INET, []): if addr['addr'] == ip_addr: return addrs[netifaces.AF_LINK][0]['addr']
Example #21
Source File: core.py From pina-colada with MIT License | 5 votes |
def get_local_mac(self, iface): return ni.ifaddresses(iface)[ni.AF_LINK][0]['addr']
Example #22
Source File: ifacesdetails.py From pythonpentest with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_addresses(interface): addrs = netifaces.ifaddresses(interface) link_addr = addrs[netifaces.AF_LINK] iface_addrs = addrs[netifaces.AF_INET] iface_dict = iface_addrs[0] link_dict = link_addr[0] hwaddr = link_dict.get('addr') iface_addr = iface_dict.get('addr') iface_broadcast = iface_dict.get('broadcast') iface_netmask = iface_dict.get('netmask') return hwaddr, iface_addr, iface_broadcast, iface_netmask
Example #23
Source File: ssh_login.py From pythonpentest with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_addresses(interface): addrs = netifaces.ifaddresses(interface) link_addr = addrs[netifaces.AF_LINK] iface_addrs = addrs[netifaces.AF_INET] iface_dict = iface_addrs[0] link_dict = link_addr[0] hwaddr = link_dict.get('addr') iface_addr = iface_dict.get('addr') iface_broadcast = iface_dict.get('broadcast') iface_netmask = iface_dict.get('netmask') return hwaddr, iface_addr, iface_broadcast, iface_netmask
Example #24
Source File: msfrpc_smb.py From pythonpentest with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_addresses(interface): addrs = netifaces.ifaddresses(interface) link_addr = addrs[netifaces.AF_LINK] iface_addrs = addrs[netifaces.AF_INET] iface_dict = iface_addrs[0] link_dict = link_addr[0] hwaddr = link_dict.get('addr') iface_addr = iface_dict.get('addr') iface_broadcast = iface_dict.get('broadcast') iface_netmask = iface_dict.get('netmask') return hwaddr, iface_addr, iface_broadcast, iface_netmask
Example #25
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 #26
Source File: network.py From pyspectator with BSD 3-Clause "New" or "Revised" License | 4 votes |
def __init__(self, monitoring_latency, stats_interval=None, ip_address=None): super().__init__(monitoring_latency) self.__name = None self.__hardware_address = None if ip_address is None: ip_address = NetworkInterface.__get_active_ip_address() self.__ip_address = ip_address self.__broadcast_address = None self.__subnet_mask = None self.__default_route = None self.__bytes_sent = 0 self.__bytes_recv = 0 # Get interface name, network mask and broadcast address if self.__ip_address is not None: for interface in nif.interfaces(): addresses = nif.ifaddresses(interface) try: af_inet = addresses[nif.AF_INET][0] if af_inet['addr'] != self.__ip_address: continue af_link = addresses[nif.AF_LINK][0] self.__name = NetworkInterface.__check_interface_name( interface ) self.__hardware_address = af_link['addr'] self.__broadcast_address = af_inet['broadcast'] self.__subnet_mask = af_inet['netmask'] break except (IndexError, KeyError): # ignore interfaces, which don't have MAC or IP continue # Get gateway address if self.name is not None: for gateway_info in nif.gateways()[nif.AF_INET]: if self.name in gateway_info: self.__default_route = gateway_info[0] break # Prepare to collect statistics if stats_interval is None: stats_interval = timedelta(hours=1) self.__bytes_sent_stats = LimitedTimeTable(stats_interval) self.__bytes_recv_stats = LimitedTimeTable(stats_interval) # Read updating values at first time self._monitoring_action()
Example #27
Source File: net.py From pykit with MIT License | 4 votes |
def get_host_ip4(iface_prefix=None, exclude_prefix=None): if iface_prefix is None: iface_prefix = [''] if type(iface_prefix) in types.StringTypes: iface_prefix = [iface_prefix] if exclude_prefix is not None: if type(exclude_prefix) in types.StringTypes: exclude_prefix = [exclude_prefix] ips = [] for ifacename in netifaces.interfaces(): matched = False for t in iface_prefix: if ifacename.startswith(t): matched = True break if exclude_prefix is not None: for ex in exclude_prefix: if ifacename.startswith(ex): matched = False break if not matched: continue addrs = netifaces.ifaddresses(ifacename) if netifaces.AF_INET in addrs and netifaces.AF_LINK in addrs: for addr in addrs[netifaces.AF_INET]: ip = str(addr['addr']) if not is_ip4_loopback(ip): ips.append(ip) return ips