Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ifconfig 376 #588

Merged
merged 38 commits into from
Feb 9, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
6bb8093
#250: implement 'iconfig' on Linux (port from old mercurial branch)
giampaolo Jun 4, 2014
96167b2
re-establish python 3 compatibility
giampaolo Jun 4, 2014
96cb3a3
Merge branch 'master' into ifconfig
giampaolo Sep 23, 2014
00da9a7
attempt to debug segfault on travis
giampaolo Sep 23, 2014
9dd4ea7
attempt to debug segfault on travis
giampaolo Sep 23, 2014
7606c48
attempt to debug travis segfault
giampaolo Sep 23, 2014
687e268
attempt to debug travis segfault
giampaolo Sep 23, 2014
4e0b55c
update doc
giampaolo Sep 24, 2014
7936127
hopefully one last attempt to fix travis
giampaolo Sep 24, 2014
47862d9
add examples/ifconfig.py
giampaolo Sep 24, 2014
697722d
expose AF_LINK
giampaolo Sep 24, 2014
36690d6
document net_if_addrs()
giampaolo Sep 24, 2014
31e4cb5
add further tests for linux
giampaolo Sep 25, 2014
d3ef6ec
fix python 3 compatibilty
giampaolo Sep 26, 2014
e4be8c7
attempt to fix trvis failure
giampaolo Sep 26, 2014
4069976
on python 3.4 turn family constants into enums
giampaolo Sep 26, 2014
6f4445c
further test using 'ip' utility on linux
giampaolo Sep 26, 2014
aabc21e
#376: implement ifconfig con Windows - still missing: MAC and broadca…
giampaolo Oct 4, 2014
b1189a3
#376: MAC address on Windows
giampaolo Oct 5, 2014
0cac87a
remove unused imports
giampaolo Jan 3, 2015
4307694
merge from master
giampaolo Feb 2, 2015
b005ead
fix import errors
giampaolo Feb 2, 2015
443f43c
fix bytes related errors on python 3
giampaolo Feb 3, 2015
f6a1bdb
use contextlib.close()
giampaolo Feb 3, 2015
559a239
modernize some code
giampaolo Feb 3, 2015
35e9a7f
provide better error message during NIC test
giampaolo Feb 3, 2015
37290de
provide better error msg
giampaolo Feb 3, 2015
c5817b6
skip failing test on travis
giampaolo Feb 3, 2015
d57c85c
Merge branch 'master' into ifconfig
giampaolo Feb 4, 2015
512579d
improve ifconfig.py script
giampaolo Feb 4, 2015
f54979e
#376: make net_if_addr() work on all other UNIX variants; also skip p…
giampaolo Jan 2, 2015
de9f48b
#376: add another test for verifying the returned NIC names
giampaolo Feb 6, 2015
a627ee7
assume primary IP address can never be None
giampaolo Feb 6, 2015
d507407
Merge branch 'master' into ifconfig-376
giampaolo Feb 7, 2015
80b04a5
#376: unify AF_LINK constant across all platforms + update doc and tests
giampaolo Feb 7, 2015
bba6b31
merge from master
giampaolo Jan 3, 2015
76cd3a6
merge from master
giampaolo Feb 9, 2015
e34c853
make flake8 happy
giampaolo Feb 9, 2015
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ Memory
* **total**: total swap memory in bytes
* **used**: used swap memory in bytes
* **free**: free swap memory in bytes
* **percent**: the percentage usage
* **percent**: the percentage usage calculated as ``(total - available) / total * 100``
* **sin**: the number of bytes the system has swapped in from disk
(cumulative)
* **sout**: the number of bytes the system has swapped out from disk
Expand Down Expand Up @@ -403,6 +403,47 @@ Network

.. versionadded:: 2.1.0

.. function:: net_if_addrs()

Return the addresses associated to each NIC (network interface card)
installed on the system as a dictionary whose keys are the NIC names and
value is a list of namedtuples for each address assigned to the NIC.
Each namedtuple includes 4 fields:

- **family**
- **address**
- **netmask**
- **broadcast**

*family* can be either
`AF_INET <http://docs.python.org//library/socket.html#socket.AF_INET>`__,
`AF_INET6 <http://docs.python.org//library/socket.html#socket.AF_INET6>`__
or :const:`psutil.AF_LINK`, which refers to a MAC address.
*address* is the primary address, *netmask* and *broadcast* may be ``None``.
Example::

>>> import psutil
>>> psutil.net_if_addrs()
{'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1'),
snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None),
snic(family=<AddressFamily.AF_PACKET: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00')],
'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255'),
snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None),
snic(family=<AddressFamily.AF_PACKET: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff')]}
>>>

See also `examples/ifconfig.py <https://github.com/giampaolo/psutil/blob/master/examples/ifconfig.py>`__
for an example application.

.. note:: if you're interested in others families (e.g. AF_BLUETOOTH) you can
use the more powerful `netifaces <https://pypi.python.org/pypi/netifaces/>`__
extension.

.. note:: you can have more than one address of the same family associated
with each interface (that's why dict values are lists).

*New in 3.0.0*


Other system info
-----------------
Expand Down Expand Up @@ -1255,3 +1296,11 @@ Constants
`man prlimit <http://linux.die.net/man/2/prlimit>`__ for futher information.

Availability: Linux

.. _const-aflink:
.. data:: AF_LINK

Constant which identifies a MAC address associated with a network interface.
To be used in conjunction with :func:`psutil.net_if_addrs()`.

*New in 3.0.0*
66 changes: 66 additions & 0 deletions examples/ifconfig.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env python

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
A clone of 'ifconfig' on UNIX.

$ python examples/ifconfig.py
lo:
IPv4 address : 127.0.0.1
broadcast : 127.0.0.1
netmask : 255.0.0.0
IPv6 address : ::1
netmask : ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff
HWADDR address : 00:00:00:00:00:00
broadcast : 00:00:00:00:00:00

wlan0:
IPv4 address : 192.168.1.3
broadcast : 192.168.1.255
netmask : 255.255.255.0
IPv6 address : fe80::c685:8ff:fe45:641%wlan0
netmask : ffff:ffff:ffff:ffff::
HWADDR address : c4:85:08:45:06:41
broadcast : ff:ff:ff:ff:ff:ff

docker0:
IPv4 address : 172.17.42.1
broadcast : 172.17.42.1
netmask : 255.255.0.0
IPv6 address : fe80::ac6d:3aff:fe0d:a19c%docker0
netmask : ffff:ffff:ffff:ffff::
HWADDR address : ae:6d:3a:0d:a1:9c
broadcast : ff:ff:ff:ff:ff:ff
"""

from __future__ import print_function
import socket

import psutil


af_map = {
socket.AF_INET: 'IPv4',
socket.AF_INET6: 'IPv6',
psutil.AF_LINK: 'HWADDR',
}


def main():
for nic, addrs in psutil.net_if_addrs().items():
print("%s:" % (nic))
for addr in addrs:
print(" %-8s" % af_map.get(addr.family, addr.family), end="")
print(" address : %s" % addr.address)
if addr.broadcast:
print(" broadcast : %s" % addr.broadcast)
if addr.netmask:
print(" netmask : %s" % addr.netmask)
print("")


if __name__ == '__main__':
main()
43 changes: 41 additions & 2 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""

from __future__ import division

import collections
import errno
import functools
Expand All @@ -31,7 +32,9 @@
from ._common import (deprecated_method as _deprecated_method,
deprecated as _deprecated,
sdiskio as _nt_sys_diskio,
snetio as _nt_sys_netio)
snetio as _nt_sys_netio,
snic as _nt_snic,
)

from ._common import (STATUS_RUNNING, # NOQA
STATUS_SLEEPING,
Expand Down Expand Up @@ -144,20 +147,22 @@
"CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
"CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
"CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
"AF_LINK",
# classes
"Process", "Popen",
# functions
"pid_exists", "pids", "process_iter", "wait_procs", # proc
"virtual_memory", "swap_memory", # memory
"cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count", # cpu
"net_io_counters", "net_connections", # network
"net_io_counters", "net_connections", "net_if_addrs", # network
"disk_io_counters", "disk_partitions", "disk_usage", # disk
"users", "boot_time", # others
]
__all__.extend(_psplatform.__extra__all__)
__author__ = "Giampaolo Rodola'"
__version__ = "3.0.0"
version_info = tuple([int(num) for num in __version__.split('.')])
AF_LINK = _psplatform.AF_LINK
_TOTAL_PHYMEM = None
_POSIX = os.name == 'posix'
_WINDOWS = os.name == 'nt'
Expand Down Expand Up @@ -1814,6 +1819,40 @@ def net_connections(kind='inet'):
return _psplatform.net_connections(kind)


def net_if_addrs():
"""Return the addresses associated to each NIC (network interface
card) installed on the system as a dictionary whose keys are the
NIC names and value is a list of namedtuples for each address
assigned to the NIC. Each namedtuple includes 4 fields:

- family
- address
- netmask
- broadcast

'family' can be either socket.AF_INET, socket.AF_INET6 or
psutil.AF_LINK, which refers to a MAC address.
'address' is the primary address, 'netmask' and 'broadcast'
may be None.
Note: you can have more than one address of the same family
associated with each interface.
"""
has_enums = sys.version_info >= (3, 4)
if has_enums:
import socket
rawlist = _psplatform.net_if_addrs()
rawlist.sort(key=lambda x: x[1]) # sort by family
ret = collections.defaultdict(list)
for name, fam, addr, mask, broadcast in rawlist:
if has_enums:
try:
fam = socket.AddressFamily(fam)
except ValueError:
pass
ret[name].append(_nt_snic(fam, addr, mask, broadcast))
return dict(ret)


# =====================================================================
# --- other system related functions
# =====================================================================
Expand Down
2 changes: 2 additions & 0 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ def socktype_to_enum(num):
# psutil.net_connections()
sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
'status', 'pid'])
# psutil.net_if_addrs()
snic = namedtuple('snic', ['family', 'address', 'netmask', 'broadcast'])


# --- namedtuples for psutil.Process methods
Expand Down
2 changes: 2 additions & 0 deletions psutil/_psbsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
}

PAGESIZE = os.sysconf("SC_PAGE_SIZE")
AF_LINK = cext_posix.AF_LINK

# extend base mem ntuple with BSD-specific memory metrics
svmem = namedtuple(
Expand Down Expand Up @@ -211,6 +212,7 @@ def net_connections(kind):
disk_usage = _psposix.disk_usage
net_io_counters = cext.net_io_counters
disk_io_counters = cext.disk_io_counters
net_if_addrs = cext_posix.net_if_addrs


def wrap_exceptions(fun):
Expand Down
4 changes: 4 additions & 0 deletions psutil/_pslinux.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
BOOT_TIME = None # set later
DEFAULT_ENCODING = sys.getdefaultencoding()
AF_LINK = socket.AF_PACKET

# ioprio_* constants http://linux.die.net/man/2/ioprio_get
IOPRIO_CLASS_NONE = 0
Expand Down Expand Up @@ -555,6 +556,9 @@ def net_io_counters():
return retdict


net_if_addrs = cext_posix.net_if_addrs


# --- disks

def disk_io_counters():
Expand Down
2 changes: 2 additions & 0 deletions psutil/_psosx.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
# --- constants

PAGESIZE = os.sysconf("SC_PAGE_SIZE")
AF_LINK = cext_posix.AF_LINK

# http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
TCP_STATUSES = {
Expand Down Expand Up @@ -171,6 +172,7 @@ def net_connections(kind='inet'):
disk_usage = _psposix.disk_usage
net_io_counters = cext.net_io_counters
disk_io_counters = cext.disk_io_counters
net_if_addrs = cext_posix.net_if_addrs


def wrap_exceptions(fun):
Expand Down
2 changes: 2 additions & 0 deletions psutil/_pssunos.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
__extra__all__ = ["CONN_IDLE", "CONN_BOUND"]

PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
AF_LINK = socket.AF_LINK

CONN_IDLE = "IDLE"
CONN_BOUND = "BOUND"
Expand Down Expand Up @@ -73,6 +74,7 @@
disk_io_counters = cext.disk_io_counters
net_io_counters = cext.net_io_counters
disk_usage = _psposix.disk_usage
net_if_addrs = cext_posix.net_if_addrs


def virtual_memory():
Expand Down
Loading