pax_global_header00006660000000000000000000000064142524507200014513gustar00rootroot0000000000000052 comment=fdc3ac75dfb6912ad93d32748e33619ecbdbe725 ifaddr-0.2.0/000077500000000000000000000000001425245072000127435ustar00rootroot00000000000000ifaddr-0.2.0/.github/000077500000000000000000000000001425245072000143035ustar00rootroot00000000000000ifaddr-0.2.0/.github/workflows/000077500000000000000000000000001425245072000163405ustar00rootroot00000000000000ifaddr-0.2.0/.github/workflows/ci.yml000066400000000000000000000020621425245072000174560ustar00rootroot00000000000000name: CI on: push: branches: [master] pull_request: jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] # At the time of writing this pypy3.10 is not available through setup-python python-version: [3.7, 3.8, 3.9, "3.10", pypy3.7, pypy3.8, pypy3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install --upgrade -r requirements-dev.txt pip install . - name: Run tests shell: bash run: | pytest if which mypy; then mypy ifaddr; fi if which black; then black --check . ; fi # Coveralls won't work here trivially because it can't ingest coverage.xml, so Codecov it is. # https://github.com/coverallsapp/github-action/issues/30 - name: Report coverage to Codecov uses: codecov/codecov-action@v1 ifaddr-0.2.0/.gitignore000066400000000000000000000010741425245072000147350ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ bin/ build/ develop-eggs/ dist/ eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .cache nosetests.xml coverage.xml # Translations *.mo # Mr Developer .mr.developer.cfg # Rope .ropeproject # Django stuff: *.log *.pot # Sphinx documentation docs/_build/ /.settings/org.eclipse.core.resources.prefs .idea ifaddr-0.2.0/.project000066400000000000000000000005501425245072000144120ustar00rootroot00000000000000 ifaddr org.python.pydev.PyDevBuilder org.python.pydev.pythonNature ifaddr-0.2.0/.pydevproject000066400000000000000000000006341425245072000154650ustar00rootroot00000000000000 /ifaddr python 2.7 Default ifaddr-0.2.0/LICENSE.txt000066400000000000000000000020741425245072000145710ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 Stefan C. Mueller Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ifaddr-0.2.0/MANIFEST.in000066400000000000000000000000471425245072000145020ustar00rootroot00000000000000include README.rst include LICENSE.txt ifaddr-0.2.0/README.rst000066400000000000000000000100511425245072000144270ustar00rootroot00000000000000ifaddr - Enumerate network interfaces/adapters and their IP addresses ===================================================================== .. image:: https://github.com/pydron/ifaddr/workflows/CI/badge.svg :target: https://github.com/pydron/ifaddr/actions?query=workflow%3ACI+branch%3Amaster .. image:: https://img.shields.io/pypi/v/ifaddr.svg :target: https://pypi.python.org/pypi/ifaddr .. image:: https://codecov.io/gh/pydron/ifaddr/branch/master/graph/badge.svg :target: https://codecov.io/gh/pydron/ifaddr `ifaddr` is a small Python library that allows you to find all the Ethernet and IP addresses of the computer. It is tested on **Linux**, **OS X**, and **Windows**. Other BSD derivatives like **OpenBSD**, **FreeBSD**, and **NetBSD** should work too, but I haven't personally tested those. **Solaris/Illumos** should also work. This library is open source and released under the MIT License. It works with Python 3.7+. You can install it with `pip install ifaddr`. It doesn't need to compile anything, so there shouldn't be any surprises. Even on Windows. Project links: * `ifaddr GitHub page `_ * `ifaddr documentation (although there isn't much to document) `_ * `ifaddr on PyPI `_ ---------------------- Let's get going! ---------------------- .. code-block:: python 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)) This will print:: IPs of network adapter H5321 gw Mobile Broadband Driver IP ('fe80::9:ebdf:30ab:39a3', 0L, 17L)/64 IP 169.254.57.163/16 IPs of network adapter Intel(R) Centrino(R) Advanced-N 6205 IP ('fe80::481f:3c9d:c3f6:93f8', 0L, 12L)/64 IP 192.168.0.51/24 IPs of network adapter Intel(R) 82579LM Gigabit Network Connection IP ('fe80::85cd:e07e:4f7a:6aa6', 0L, 11L)/64 IP 192.168.0.53/24 IPs of network adapter Software Loopback Interface 1 IP ('::1', 0L, 0L)/128 IP 127.0.0.1/8 You get both IPv4 and IPv6 addresses. The later complete with flowinfo and scope_id. If you wish to include network interfaces that do not have a configured IP addresss, pass the `include_unconfigured` parameter to `get_adapters()`. Adapters with no configured IP addresses will have an zero-length `ips` property. For example: .. code-block:: python import ifaddr adapters = ifaddr.get_adapters(include_unconfigured=True) for adapter in adapters: print("IPs of network adapter " + adapter.nice_name) if adapter.ips: for ip in adapter.ips: print(" %s/%s" % (ip.ip, ip.network_prefix)) else: print(" No IPs configured") --------- Changelog --------- 0.2.0 ----- * Added an option to include IP-less adapters, thanks to memory * Fixed a bug where an interface's name was `bytes`, not `str`, on Windows * Added an implementation of `netifaces.interfaces()` (available through `ifaddr.netifaces.interfaces()`) * Added type hints Backwards incompatible/breaking changes: * Dropped Python 3.6 support 0.1.7 ----- * Fixed Python 3 compatibility in the examples, thanks to Tristan Stenner and Josef Schlehofer * Exposed network interface indexes in Adapter.index, thanks to Dmitry Tantsur * Added the license file to distributions on PyPI, thanks to Tomáš Chvátal * Fixed Illumos/Solaris compatibility based on a patch proposed by Jorge Schrauwen * Set up universal wheels, ifaddr will have both source and wheel distributions on PyPI from now on ------------ Alternatives ------------ Alastair Houghton develops `netifaces `_ which can do everything this library can, and more. The only drawback is that it needs to be compiled, which can make the installation difficult. As of ifaddr 0.2.0 we implement the equivalent of `netifaces.interfaces()`. It's available through `ifaddr.netifaces.interfaces()`. ifaddr-0.2.0/doc/000077500000000000000000000000001425245072000135105ustar00rootroot00000000000000ifaddr-0.2.0/doc/_static/000077500000000000000000000000001425245072000151365ustar00rootroot00000000000000ifaddr-0.2.0/doc/_static/readme.txt000066400000000000000000000000521425245072000171310ustar00rootroot00000000000000Static content of html content goes here. ifaddr-0.2.0/doc/conf.py000066400000000000000000000206651425245072000150200ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Pydron documentation build configuration file, created by # sphinx-quickstart on Thu May 23 13:41:54 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.graphviz', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'ifaddr' copyright = u'2014, Stefan C. Mueller' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1.1' # The full version, including alpha/beta/rc tags. release = '0.1.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinxdoc' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pythondoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'python.tex', u'ifaddr Documentation', u'Stefan C. Mueller', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [('index', 'python', u'ifaddr Documentation', [u'Stefan C. Mueller'], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( 'index', 'python', u'ifaddr Documentation', u'Stefan C. Mueller', 'python', 'Enumerates all IP addresses on all network adapters of the system.', 'Miscellaneous', ), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} def skip(app, what, name, obj, skip, options): if name == "__init__": return False return skip def setup(app): app.connect("autodoc-skip-member", skip) ifaddr-0.2.0/doc/index.rst000066400000000000000000000046271425245072000153620ustar00rootroot00000000000000 ifaddr - Enumerate IP addresses on the local network adapters ============================================================= `ifaddr` is a small Python library that allows you to find all the IP addresses of the computer. It is tested on **Linux**, **OS X**, and **Windows**. Other BSD derivatives like **OpenBSD**, **FreeBSD**, and **NetBSD** should work too, but I haven't personally tested those. This library is open source and released under the MIT License. You can install it with `pip install ifaddr`. It doesn't need to compile anything, so there shouldn't be any surprises. Even on Windows. ---------------------- Let's get going! ---------------------- .. code-block:: python 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)) This will print: .. code-block:: none IPs of network adapter H5321 gw Mobile Broadband Driver IP ('fe80::9:ebdf:30ab:39a3', 0L, 17L)/64 IP 169.254.57.163/16 IPs of network adapter Intel(R) Centrino(R) Advanced-N 6205 IP ('fe80::481f:3c9d:c3f6:93f8', 0L, 12L)/64 IP 192.168.0.51/24 IPs of network adapter Intel(R) 82579LM Gigabit Network Connection IP ('fe80::85cd:e07e:4f7a:6aa6', 0L, 11L)/64 IP 192.168.0.53/24 IPs of network adapter Software Loopback Interface 1 IP ('::1', 0L, 0L)/128 IP 127.0.0.1/8 You get both IPv4 and IPv6 addresses. The later complete with flowinfo and scope_id. ----- API ----- The library has only one function: .. py:function:: ifaddr.get_adapters() Receives all the network adapters with their IP addresses. :returns: List of :class:`ifaddr.Adapter` instances in the order they are provided by the operating system. And two simple classes: .. autoclass:: ifaddr.Adapter :members: name, ips, nice_name .. autoclass:: ifaddr.IP :members: ip, network_prefix, nice_name ----------------------------------- Bug Reports and other contributions ----------------------------------- This project is hosted here `ifaddr github page `_. ------------ Alternatives ------------ Alastair Houghton develops `netifaces `_ which can do everything this library can, and more. The only drawback is that it needs to be compiled, which can make the installation difficult. ifaddr-0.2.0/ifaddr/000077500000000000000000000000001425245072000141745ustar00rootroot00000000000000ifaddr-0.2.0/ifaddr/__init__.py000066400000000000000000000025671425245072000163170ustar00rootroot00000000000000# Copyright (c) 2014 Stefan C. Mueller # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import os from ifaddr._shared import Adapter, IP if os.name == "nt": from ifaddr._win32 import get_adapters elif os.name == "posix": from ifaddr._posix import get_adapters else: raise RuntimeError("Unsupported Operating System: %s" % os.name) __all__ = ['Adapter', 'IP', 'get_adapters'] ifaddr-0.2.0/ifaddr/_posix.py000066400000000000000000000072111425245072000160500ustar00rootroot00000000000000# Copyright (c) 2014 Stefan C. Mueller # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import os import ctypes.util import ipaddress import collections import socket from typing import Iterable, Optional import ifaddr._shared as shared # from ifaddr._shared import sockaddr, Interface, sockaddr_to_ip, ipv6_prefixlength class ifaddrs(ctypes.Structure): pass ifaddrs._fields_ = [ ('ifa_next', ctypes.POINTER(ifaddrs)), ('ifa_name', ctypes.c_char_p), ('ifa_flags', ctypes.c_uint), ('ifa_addr', ctypes.POINTER(shared.sockaddr)), ('ifa_netmask', ctypes.POINTER(shared.sockaddr)), ] libc = ctypes.CDLL(ctypes.util.find_library("socket" if os.uname()[0] == "SunOS" else "c"), use_errno=True) # type: ignore def get_adapters(include_unconfigured: bool = False) -> Iterable[shared.Adapter]: addr0 = addr = ctypes.POINTER(ifaddrs)() retval = libc.getifaddrs(ctypes.byref(addr)) if retval != 0: eno = ctypes.get_errno() raise OSError(eno, os.strerror(eno)) ips = collections.OrderedDict() def add_ip(adapter_name: str, ip: Optional[shared.IP]) -> None: if adapter_name not in ips: index = None # type: Optional[int] try: # Mypy errors on this when the Windows CI runs: # error: Module has no attribute "if_nametoindex" index = socket.if_nametoindex(adapter_name) # type: ignore except (OSError, AttributeError): pass ips[adapter_name] = shared.Adapter(adapter_name, adapter_name, [], index=index) if ip is not None: ips[adapter_name].ips.append(ip) while addr: name = addr[0].ifa_name.decode(encoding='UTF-8') ip_addr = shared.sockaddr_to_ip(addr[0].ifa_addr) if ip_addr: if addr[0].ifa_netmask and not addr[0].ifa_netmask[0].sa_familiy: addr[0].ifa_netmask[0].sa_familiy = addr[0].ifa_addr[0].sa_familiy netmask = shared.sockaddr_to_ip(addr[0].ifa_netmask) if isinstance(netmask, tuple): netmaskStr = str(netmask[0]) prefixlen = shared.ipv6_prefixlength(ipaddress.IPv6Address(netmaskStr)) else: assert netmask is not None, f'sockaddr_to_ip({addr[0].ifa_netmask}) returned None' netmaskStr = str('0.0.0.0/' + netmask) prefixlen = ipaddress.IPv4Network(netmaskStr).prefixlen ip = shared.IP(ip_addr, prefixlen, name) add_ip(name, ip) else: if include_unconfigured: add_ip(name, None) addr = addr[0].ifa_next libc.freeifaddrs(addr0) return ips.values() ifaddr-0.2.0/ifaddr/_shared.py000066400000000000000000000162321425245072000161570ustar00rootroot00000000000000# Copyright (c) 2014 Stefan C. Mueller # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import ctypes import socket import ipaddress import platform from typing import List, Optional, Tuple, Union class Adapter(object): """ Represents a network interface device controller (NIC), such as a network card. An adapter can have multiple IPs. On Linux aliasing (multiple IPs per physical NIC) is implemented by creating 'virtual' adapters, each represented by an instance of this class. Each of those 'virtual' adapters can have both a IPv4 and an IPv6 IP address. """ def __init__(self, name: str, nice_name: str, ips: List['IP'], index: Optional[int] = None) -> None: #: Unique name that identifies the adapter in the system. #: On Linux this is of the form of `eth0` or `eth0:1`, on #: Windows it is a UUID in string representation, such as #: `{846EE342-7039-11DE-9D20-806E6F6E6963}`. self.name = name #: Human readable name of the adpater. On Linux this #: is currently the same as :attr:`name`. On Windows #: this is the name of the device. self.nice_name = nice_name #: List of :class:`ifaddr.IP` instances in the order they were #: reported by the system. self.ips = ips #: Adapter index as used by some API (e.g. IPv6 multicast group join). self.index = index def __repr__(self) -> str: return "Adapter(name={name}, nice_name={nice_name}, ips={ips}, index={index})".format( name=repr(self.name), nice_name=repr(self.nice_name), ips=repr(self.ips), index=repr(self.index) ) # Type of an IPv4 address (a string in "xxx.xxx.xxx.xxx" format) _IPv4Address = str # Type of an IPv6 address (a three-tuple `(ip, flowinfo, scope_id)`) _IPv6Address = Tuple[str, int, int] class IP(object): """ Represents an IP address of an adapter. """ def __init__(self, ip: Union[_IPv4Address, _IPv6Address], network_prefix: int, nice_name: str) -> None: #: IP address. For IPv4 addresses this is a string in #: "xxx.xxx.xxx.xxx" format. For IPv6 addresses this #: is a three-tuple `(ip, flowinfo, scope_id)`, where #: `ip` is a string in the usual collon separated #: hex format. self.ip = ip #: Number of bits of the IP that represent the #: network. For a `255.255.255.0` netmask, this #: number would be `24`. self.network_prefix = network_prefix #: Human readable name for this IP. #: On Linux is this currently the same as the adapter name. #: On Windows this is the name of the network connection #: as configured in the system control panel. self.nice_name = nice_name @property def is_IPv4(self) -> bool: """ Returns `True` if this IP is an IPv4 address and `False` if it is an IPv6 address. """ return not isinstance(self.ip, tuple) @property def is_IPv6(self) -> bool: """ Returns `True` if this IP is an IPv6 address and `False` if it is an IPv4 address. """ return isinstance(self.ip, tuple) def __repr__(self) -> str: return "IP(ip={ip}, network_prefix={network_prefix}, nice_name={nice_name})".format( ip=repr(self.ip), network_prefix=repr(self.network_prefix), nice_name=repr(self.nice_name) ) if platform.system() == "Darwin" or "BSD" in platform.system(): # BSD derived systems use marginally different structures # than either Linux or Windows. # I still keep it in `shared` since we can use # both structures equally. class sockaddr(ctypes.Structure): _fields_ = [ ('sa_len', ctypes.c_uint8), ('sa_familiy', ctypes.c_uint8), ('sa_data', ctypes.c_uint8 * 14), ] class sockaddr_in(ctypes.Structure): _fields_ = [ ('sa_len', ctypes.c_uint8), ('sa_familiy', ctypes.c_uint8), ('sin_port', ctypes.c_uint16), ('sin_addr', ctypes.c_uint8 * 4), ('sin_zero', ctypes.c_uint8 * 8), ] class sockaddr_in6(ctypes.Structure): _fields_ = [ ('sa_len', ctypes.c_uint8), ('sa_familiy', ctypes.c_uint8), ('sin6_port', ctypes.c_uint16), ('sin6_flowinfo', ctypes.c_uint32), ('sin6_addr', ctypes.c_uint8 * 16), ('sin6_scope_id', ctypes.c_uint32), ] else: class sockaddr(ctypes.Structure): # type: ignore _fields_ = [('sa_familiy', ctypes.c_uint16), ('sa_data', ctypes.c_uint8 * 14)] class sockaddr_in(ctypes.Structure): # type: ignore _fields_ = [ ('sin_familiy', ctypes.c_uint16), ('sin_port', ctypes.c_uint16), ('sin_addr', ctypes.c_uint8 * 4), ('sin_zero', ctypes.c_uint8 * 8), ] class sockaddr_in6(ctypes.Structure): # type: ignore _fields_ = [ ('sin6_familiy', ctypes.c_uint16), ('sin6_port', ctypes.c_uint16), ('sin6_flowinfo', ctypes.c_uint32), ('sin6_addr', ctypes.c_uint8 * 16), ('sin6_scope_id', ctypes.c_uint32), ] def sockaddr_to_ip(sockaddr_ptr: 'ctypes.pointer[sockaddr]') -> Optional[Union[_IPv4Address, _IPv6Address]]: if sockaddr_ptr: if sockaddr_ptr[0].sa_familiy == socket.AF_INET: ipv4 = ctypes.cast(sockaddr_ptr, ctypes.POINTER(sockaddr_in)) ippacked = bytes(bytearray(ipv4[0].sin_addr)) ip = str(ipaddress.ip_address(ippacked)) return ip elif sockaddr_ptr[0].sa_familiy == socket.AF_INET6: ipv6 = ctypes.cast(sockaddr_ptr, ctypes.POINTER(sockaddr_in6)) flowinfo = ipv6[0].sin6_flowinfo ippacked = bytes(bytearray(ipv6[0].sin6_addr)) ip = str(ipaddress.ip_address(ippacked)) scope_id = ipv6[0].sin6_scope_id return (ip, flowinfo, scope_id) return None def ipv6_prefixlength(address: ipaddress.IPv6Address) -> int: prefix_length = 0 for i in range(address.max_prefixlen): if int(address) >> i & 1: prefix_length = prefix_length + 1 return prefix_length ifaddr-0.2.0/ifaddr/_win32.py000066400000000000000000000117501425245072000156530ustar00rootroot00000000000000# Copyright (c) 2014 Stefan C. Mueller # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import ctypes from ctypes import wintypes from typing import Iterable, List import ifaddr._shared as shared NO_ERROR = 0 ERROR_BUFFER_OVERFLOW = 111 MAX_ADAPTER_NAME_LENGTH = 256 MAX_ADAPTER_DESCRIPTION_LENGTH = 128 MAX_ADAPTER_ADDRESS_LENGTH = 8 AF_UNSPEC = 0 class SOCKET_ADDRESS(ctypes.Structure): _fields_ = [('lpSockaddr', ctypes.POINTER(shared.sockaddr)), ('iSockaddrLength', wintypes.INT)] class IP_ADAPTER_UNICAST_ADDRESS(ctypes.Structure): pass IP_ADAPTER_UNICAST_ADDRESS._fields_ = [ ('Length', wintypes.ULONG), ('Flags', wintypes.DWORD), ('Next', ctypes.POINTER(IP_ADAPTER_UNICAST_ADDRESS)), ('Address', SOCKET_ADDRESS), ('PrefixOrigin', ctypes.c_uint), ('SuffixOrigin', ctypes.c_uint), ('DadState', ctypes.c_uint), ('ValidLifetime', wintypes.ULONG), ('PreferredLifetime', wintypes.ULONG), ('LeaseLifetime', wintypes.ULONG), ('OnLinkPrefixLength', ctypes.c_uint8), ] class IP_ADAPTER_ADDRESSES(ctypes.Structure): pass IP_ADAPTER_ADDRESSES._fields_ = [ ('Length', wintypes.ULONG), ('IfIndex', wintypes.DWORD), ('Next', ctypes.POINTER(IP_ADAPTER_ADDRESSES)), ('AdapterName', ctypes.c_char_p), ('FirstUnicastAddress', ctypes.POINTER(IP_ADAPTER_UNICAST_ADDRESS)), ('FirstAnycastAddress', ctypes.c_void_p), ('FirstMulticastAddress', ctypes.c_void_p), ('FirstDnsServerAddress', ctypes.c_void_p), ('DnsSuffix', ctypes.c_wchar_p), ('Description', ctypes.c_wchar_p), ('FriendlyName', ctypes.c_wchar_p), ] iphlpapi = ctypes.windll.LoadLibrary("Iphlpapi") # type: ignore def enumerate_interfaces_of_adapter( nice_name: str, address: IP_ADAPTER_UNICAST_ADDRESS ) -> Iterable[shared.IP]: # Iterate through linked list and fill list addresses = [] # type: List[IP_ADAPTER_UNICAST_ADDRESS] while True: addresses.append(address) if not address.Next: break address = address.Next[0] for address in addresses: ip = shared.sockaddr_to_ip(address.Address.lpSockaddr) assert ip is not None, f'sockaddr_to_ip({address.Address.lpSockaddr}) returned None' network_prefix = address.OnLinkPrefixLength yield shared.IP(ip, network_prefix, nice_name) def get_adapters(include_unconfigured: bool = False) -> Iterable[shared.Adapter]: # Call GetAdaptersAddresses() with error and buffer size handling addressbuffersize = wintypes.ULONG(15 * 1024) retval = ERROR_BUFFER_OVERFLOW while retval == ERROR_BUFFER_OVERFLOW: addressbuffer = ctypes.create_string_buffer(addressbuffersize.value) retval = iphlpapi.GetAdaptersAddresses( wintypes.ULONG(AF_UNSPEC), wintypes.ULONG(0), None, ctypes.byref(addressbuffer), ctypes.byref(addressbuffersize), ) if retval != NO_ERROR: raise ctypes.WinError() # type: ignore # Iterate through adapters fill array address_infos = [] # type: List[IP_ADAPTER_ADDRESSES] address_info = IP_ADAPTER_ADDRESSES.from_buffer(addressbuffer) while True: address_infos.append(address_info) if not address_info.Next: break address_info = address_info.Next[0] # Iterate through unicast addresses result = [] # type: List[shared.Adapter] for adapter_info in address_infos: # We don't expect non-ascii characters here, so encoding shouldn't matter name = adapter_info.AdapterName.decode() nice_name = adapter_info.Description index = adapter_info.IfIndex if adapter_info.FirstUnicastAddress: ips = enumerate_interfaces_of_adapter( adapter_info.FriendlyName, adapter_info.FirstUnicastAddress[0] ) ips = list(ips) result.append(shared.Adapter(name, nice_name, ips, index=index)) elif include_unconfigured: result.append(shared.Adapter(name, nice_name, [], index=index)) return result ifaddr-0.2.0/ifaddr/netifaces.py000066400000000000000000000003151425245072000165060ustar00rootroot00000000000000# netifaces compatibility layer import ifaddr from typing import List def interfaces() -> List[str]: adapters = ifaddr.get_adapters(include_unconfigured=True) return [a.name for a in adapters] ifaddr-0.2.0/ifaddr/py.typed000066400000000000000000000000001425245072000156610ustar00rootroot00000000000000ifaddr-0.2.0/ifaddr/test_ifaddr.py000066400000000000000000000024411425245072000170370ustar00rootroot00000000000000# Copyright (C) 2015 Stefan C. Mueller import unittest import pytest import ifaddr import ifaddr.netifaces try: import netifaces except ImportError: skip_netifaces = True else: skip_netifaces = False class TestIfaddr(unittest.TestCase): """ Unittests for :mod:`ifaddr`. There isn't much unit-testing that can be done without making assumptions on the system or mocking of operating system APIs. So this just contains a sanity check for the moment. """ def test_get_adapters_contains_localhost(self) -> None: 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)) @pytest.mark.skipif(skip_netifaces, reason='netifaces not installed') def test_netifaces_compatibility() -> None: interfaces = ifaddr.netifaces.interfaces() assert interfaces == netifaces.interfaces() # TODO: implement those as well # for interface in interfaces: # print(interface) # assert ifaddr.netifaces.ifaddresses(interface) == netifaces.ifaddresses(interface) # assert ifaddr.netifaces.gateways() == netifaces.gateways() ifaddr-0.2.0/mypy.ini000066400000000000000000000007561425245072000144520ustar00rootroot00000000000000[mypy] # The warn_unused_configs flag may be useful to debug misspelled section names. warn_unused_configs = True # Shows a warning when returning a value with type 'Any' from # a function declared with a non-'Any' return type. warn_return_any = True # Disallows defining functions without type annotations # or with incomplete type annotations. disallow_untyped_defs = True [mypy-netifaces.*] # Suppresses error messages about imports that cannot be resolved. ignore_missing_imports = True ifaddr-0.2.0/pyproject.toml000066400000000000000000000001631425245072000156570ustar00rootroot00000000000000[tool.black] line-length = 110 target_version = ['py37', 'py38', 'py39', 'py310'] skip_string_normalization = true ifaddr-0.2.0/pytest.ini000066400000000000000000000001771425245072000150010ustar00rootroot00000000000000[pytest] addopts = -v --cov-report term --cov-report html --cov-report xml --cov-report term-missing --cov=ifaddr --cov-branch ifaddr-0.2.0/requirements-dev.txt000066400000000000000000000004331425245072000170030ustar00rootroot00000000000000black;implementation_name=="cpython" mypy;implementation_name=="cpython" # netifaces only provides 64-bit Windows wheels for Python 3.6 and 3.7 and we use 64-bit CI builds netifaces;python_version=='3.7' and platform_system=='Windows' or platform_system!='Windows' pytest pytest-cov ifaddr-0.2.0/setup.cfg000066400000000000000000000001061425245072000145610ustar00rootroot00000000000000[build_sphinx] source-dir = doc build-dir = build/doc all_files = 1 ifaddr-0.2.0/setup.py000066400000000000000000000042401425245072000144550ustar00rootroot00000000000000# Copyright (c) 2014 Stefan C. Mueller # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import os.path from setuptools import setup, find_packages if os.path.exists('README.rst'): with open('README.rst') as f: long_description = f.read() else: long_description = "" setup( name='ifaddr', version='0.2.0', description='Cross-platform network interface and IP address enumeration library', long_description=long_description, author='Stefan C. Mueller', author_email='scm@smurn.org', url='https://github.com/pydron/ifaddr', packages=find_packages(), package_data={'ifaddr': ['py.typed']}, license='MIT', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: System :: Networking', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', ], keywords=['network interfaces', 'network adapters', 'network addresses', 'IP addresses'], )