pax_global_header 0000666 0000000 0000000 00000000064 13666763347 0014537 g ustar 00root root 0000000 0000000 52 comment=2aa93d3b2c59745d361c8f822c2e081d3a7d167f
ifaddr-0.1.7/ 0000775 0000000 0000000 00000000000 13666763347 0012775 5 ustar 00root root 0000000 0000000 ifaddr-0.1.7/.github/ 0000775 0000000 0000000 00000000000 13666763347 0014335 5 ustar 00root root 0000000 0000000 ifaddr-0.1.7/.github/workflows/ 0000775 0000000 0000000 00000000000 13666763347 0016372 5 ustar 00root root 0000000 0000000 ifaddr-0.1.7/.github/workflows/ci.yml 0000664 0000000 0000000 00000001507 13666763347 0017513 0 ustar 00root root 0000000 0000000 name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: [2.7, 3.5, 3.6, 3.7, 3.8, pypy2, pypy3]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install --upgrade -r requirements-dev.txt
pip install .
- name: Run tests
run: |
pytest
# 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.1.7/.gitignore 0000664 0000000 0000000 00000001074 13666763347 0014767 0 ustar 00root root 0000000 0000000 # 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.1.7/.project 0000664 0000000 0000000 00000000550 13666763347 0014444 0 ustar 00root root 0000000 0000000
ifaddrorg.python.pydev.PyDevBuilderorg.python.pydev.pythonNature
ifaddr-0.1.7/.pydevproject 0000664 0000000 0000000 00000000634 13666763347 0015517 0 ustar 00root root 0000000 0000000
/ifaddrpython 2.7Default
ifaddr-0.1.7/LICENSE.txt 0000664 0000000 0000000 00000002074 13666763347 0014623 0 ustar 00root root 0000000 0000000 The 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.1.7/MANIFEST.in 0000664 0000000 0000000 00000000047 13666763347 0014534 0 ustar 00root root 0000000 0000000 include README.rst
include LICENSE.txt
ifaddr-0.1.7/README.rst 0000664 0000000 0000000 00000005723 13666763347 0014473 0 ustar 00root root 0000000 0000000 ifaddr - 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
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 2.7 and 3.5+.
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.
---------
Changelog
---------
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.
ifaddr-0.1.7/doc/ 0000775 0000000 0000000 00000000000 13666763347 0013542 5 ustar 00root root 0000000 0000000 ifaddr-0.1.7/doc/_static/ 0000775 0000000 0000000 00000000000 13666763347 0015170 5 ustar 00root root 0000000 0000000 ifaddr-0.1.7/doc/_static/readme.txt 0000664 0000000 0000000 00000000052 13666763347 0017163 0 ustar 00root root 0000000 0000000 Static content of html content goes here.
ifaddr-0.1.7/doc/conf.py 0000664 0000000 0000000 00000020620 13666763347 0015041 0 ustar 00root root 0000000 0000000 # -*- 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.1.7/doc/index.rst 0000664 0000000 0000000 00000004627 13666763347 0015414 0 ustar 00root root 0000000 0000000
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.1.7/ifaddr/ 0000775 0000000 0000000 00000000000 13666763347 0014226 5 ustar 00root root 0000000 0000000 ifaddr-0.1.7/ifaddr/__init__.py 0000664 0000000 0000000 00000002567 13666763347 0016351 0 ustar 00root root 0000000 0000000 # 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.1.7/ifaddr/_posix.py 0000664 0000000 0000000 00000007026 13666763347 0016106 0 ustar 00root root 0000000 0000000 # 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 sys
import os
import ctypes.util
import ipaddress
import collections
import socket
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)
def get_adapters():
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, ip):
if not adapter_name in ips:
try:
index = socket.if_nametoindex(adapter_name)
except (OSError, AttributeError):
index = None
ips[adapter_name] = shared.Adapter(adapter_name, adapter_name, [],
index=index)
ips[adapter_name].ips.append(ip)
while addr:
name = addr[0].ifa_name
if sys.version_info[0] > 2:
name = name.decode(encoding='UTF-8')
ip = shared.sockaddr_to_ip(addr[0].ifa_addr)
if ip:
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):
netmask = netmask[0]
if sys.version_info[0] > 2:
netmaskStr = str(netmask)
else:
netmaskStr = unicode(netmask)
prefixlen = shared.ipv6_prefixlength(ipaddress.IPv6Address(netmaskStr))
else:
if sys.version_info[0] > 2:
netmaskStr = str('0.0.0.0/' + netmask)
else:
netmaskStr = unicode('0.0.0.0/' + netmask)
prefixlen = ipaddress.IPv4Network(netmaskStr).prefixlen
ip = shared.IP(ip, prefixlen, name)
add_ip(name, ip)
addr = addr[0].ifa_next
libc.freeifaddrs(addr0)
return ips.values()
ifaddr-0.1.7/ifaddr/_shared.py 0000664 0000000 0000000 00000015351 13666763347 0016212 0 ustar 00root root 0000000 0000000 # 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
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, nice_name, ips, index=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):
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)
)
class IP(object):
"""
Represents an IP address of an adapter.
"""
def __init__(self, ip, network_prefix, nice_name):
#: 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):
"""
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):
"""
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):
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):
_fields_= [('sa_familiy', ctypes.c_uint16),
('sa_data', ctypes.c_uint8 * 14)]
class sockaddr_in(ctypes.Structure):
_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):
_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):
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):
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.1.7/ifaddr/_win32.py 0000664 0000000 0000000 00000011526 13666763347 0015706 0 ustar 00root root 0000000 0000000 # 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
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.POINTER(None)),
('FirstMulticastAddress', ctypes.POINTER(None)),
('FirstDnsServerAddress', ctypes.POINTER(None)),
('DnsSuffix', ctypes.c_wchar_p),
('Description', ctypes.c_wchar_p),
('FriendlyName', ctypes.c_wchar_p)
]
iphlpapi = ctypes.windll.LoadLibrary("Iphlpapi")
def enumerate_interfaces_of_adapter(nice_name, address):
# Iterate through linked list and fill list
addresses = []
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)
network_prefix = address.OnLinkPrefixLength
yield shared.IP(ip, network_prefix, nice_name)
def get_adapters():
# 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()
# Iterate through adapters fill array
address_infos = []
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 = []
for adapter_info in address_infos:
name = adapter_info.AdapterName
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))
return result
ifaddr-0.1.7/ifaddr/test_ifaddr.py 0000664 0000000 0000000 00000001262 13666763347 0017071 0 ustar 00root root 0000000 0000000 # Copyright (C) 2015 Stefan C. Mueller
import unittest
import ifaddr
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):
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))
ifaddr-0.1.7/pytest.ini 0000664 0000000 0000000 00000000177 13666763347 0015033 0 ustar 00root root 0000000 0000000 [pytest]
addopts = -v --cov-report term --cov-report html --cov-report xml --cov-report term-missing --cov=ifaddr --cov-branch
ifaddr-0.1.7/requirements-dev.txt 0000664 0000000 0000000 00000000022 13666763347 0017027 0 ustar 00root root 0000000 0000000 pytest
pytest-cov
ifaddr-0.1.7/setup.cfg 0000664 0000000 0000000 00000000140 13666763347 0014611 0 ustar 00root root 0000000 0000000 [build_sphinx]
source-dir = doc
build-dir = build/doc
all_files = 1
[wheel]
universal = True
ifaddr-0.1.7/setup.py 0000664 0000000 0000000 00000004425 13666763347 0014514 0 ustar 00root root 0000000 0000000 # 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.1.7',
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(),
license='MIT',
install_requires = ['ipaddress;python_version<"3.3"'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Topic :: System :: Networking',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
keywords=['network interfaces', 'network adapters', 'network addresses', 'IP addresses'],
)