pax_global_header00006660000000000000000000000064134032715050014512gustar00rootroot0000000000000052 comment=9fae414dfab97e109bf089773a075df83b7ae91a ifaddr-0.1.6/000077500000000000000000000000001340327150500127475ustar00rootroot00000000000000ifaddr-0.1.6/.gitignore000066400000000000000000000010731340327150500147400ustar00rootroot00000000000000# 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 .ideaifaddr-0.1.6/.project000066400000000000000000000005501340327150500144160ustar00rootroot00000000000000 ifaddr org.python.pydev.PyDevBuilder org.python.pydev.pythonNature ifaddr-0.1.6/.pydevproject000066400000000000000000000006341340327150500154710ustar00rootroot00000000000000 /ifaddr python 2.7 Default ifaddr-0.1.6/LICENSE.txt000066400000000000000000000020741340327150500145750ustar00rootroot00000000000000The 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.6/MANIFEST.in000066400000000000000000000000231340327150500145000ustar00rootroot00000000000000include README.rst ifaddr-0.1.6/README.rst000066400000000000000000000042521340327150500144410ustar00rootroot00000000000000 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:: python 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. ------------- Documentation ------------- The complete documentation (there isn't much to document) can be found here: `ifaddr Documentation `_. ----------------------------------- 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.6/doc/000077500000000000000000000000001340327150500135145ustar00rootroot00000000000000ifaddr-0.1.6/doc/_static/000077500000000000000000000000001340327150500151425ustar00rootroot00000000000000ifaddr-0.1.6/doc/_static/readme.txt000066400000000000000000000000511340327150500171340ustar00rootroot00000000000000Static content of html content goes here.ifaddr-0.1.6/doc/conf.py000066400000000000000000000206241340327150500150170ustar00rootroot00000000000000# -*- 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.6/doc/index.rst000066400000000000000000000046631340327150500153660ustar00rootroot00000000000000 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.6/ifaddr/000077500000000000000000000000001340327150500142005ustar00rootroot00000000000000ifaddr-0.1.6/ifaddr/__init__.py000066400000000000000000000025741340327150500163210ustar00rootroot00000000000000# 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.6/ifaddr/_posix.py000066400000000000000000000064371340327150500160650ustar00rootroot00000000000000# 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 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("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: ips[adapter_name] = shared.Adapter(adapter_name, adapter_name, []) 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.6/ifaddr/_shared.py000066400000000000000000000154141340327150500161640ustar00rootroot00000000000000# 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): #: 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 def __repr__(self): return "Adapter(name={name}, nice_name={nice_name}, ips={ips})".format( name = repr(self.name), nice_name = repr(self.nice_name), ips = repr(self.ips) ) 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.6/ifaddr/_win32.py000066400000000000000000000114741340327150500156620ustar00rootroot00000000000000# 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 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)) return result ifaddr-0.1.6/ifaddr/test_ifaddr.py000066400000000000000000000013251340327150500170430ustar00rootroot00000000000000# 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.6/setup.cfg000066400000000000000000000001071340327150500145660ustar00rootroot00000000000000[build_sphinx] source-dir = doc build-dir = build/doc all_files = 1 ifaddr-0.1.6/setup.py000066400000000000000000000032451340327150500144650ustar00rootroot00000000000000# 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.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.6', description='Enumerates all IP addresses on all network adapters of the system.', long_description=long_description, author='Stefan C. Mueller', author_email='scm@smurn.org', url='https://github.com/pydron/ifaddr', packages = find_packages(), install_requires = ['ipaddress'] if sys.version_info[:2] < (3, 3) else [], )