Debian Codegraph @

psutil/arch/bsd/net.c

raw
1 /*
2 * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 #include <Python.h>
8 #include <sys/sysctl.h>
9 #include <string.h>
10 #include <net/if.h>
11 #include <net/if_dl.h>
12 #include <net/route.h>
13
14 #include "../../arch/all/init.h"
15
16
17 PyObject *
18 psutil_net_io_counters(PyObject *self, PyObject *args) {
19 char *buf = NULL, *lim, *next;
20 struct if_msghdr *ifm;
21 int mib[6];
22 size_t len;
23 PyObject *py_retdict = PyDict_New();
24 PyObject *py_ifc_info = NULL;
25
26 if (py_retdict == NULL)
27 return NULL;
28
29 mib[0] = CTL_NET; // networking subsystem
30 mib[1] = PF_ROUTE; // type of information
31 mib[2] = 0; // protocol (IPPROTO_xxx)
32 mib[3] = 0; // address family
33 mib[4] = NET_RT_IFLIST; // operation
34 mib[5] = 0;
35
36 if (psutil_sysctl_malloc(mib, 6, &buf, &len) != 0)
37 goto error;
38
39 lim = buf + len;
40
41 for (next = buf; next < lim;) {
42 py_ifc_info = NULL;
43 ifm = (struct if_msghdr *)next;
44 next += ifm->ifm_msglen;
45
46 if (ifm->ifm_type == RTM_IFINFO) {
47 struct if_msghdr *if2m = (struct if_msghdr *)ifm;
48 struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
49 char ifc_name[32];
50
51 strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
52 ifc_name[sdl->sdl_nlen] = '\0';
53
54 // XXX: ignore usbus interfaces:
55 // http://lists.freebsd.org/pipermail/freebsd-current/
56 // 2011-October/028752.html
57 // 'ifconfig -a' doesn't show them, nor do we.
58 if (strncmp(ifc_name, "usbus", 5) == 0)
59 continue;
60
61 py_ifc_info = Py_BuildValue(
62 "(kkkkkkki)",
63 if2m->ifm_data.ifi_obytes,
64 if2m->ifm_data.ifi_ibytes,
65 if2m->ifm_data.ifi_opackets,
66 if2m->ifm_data.ifi_ipackets,
67 if2m->ifm_data.ifi_ierrors,
68 if2m->ifm_data.ifi_oerrors,
69 if2m->ifm_data.ifi_iqdrops,
70 #ifdef _IFI_OQDROPS
71 if2m->ifm_data.ifi_oqdrops
72 #else
73 0
74 #endif
75 );
76 if (!py_ifc_info)
77 goto error;
78 if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info) != 0)
79 goto error;
80 Py_CLEAR(py_ifc_info);
81 }
82 }
83
84 free(buf);
85 return py_retdict;
86
87 error:
88 Py_XDECREF(py_ifc_info);
89 Py_DECREF(py_retdict);
90 free(buf);
91 return NULL;
92 }