Skip to content

Commit

Permalink
Fix #517 by testing ksp->ks_name is a network interface
Browse files Browse the repository at this point in the history
instead of testing ksp->ks_module is 'link'
  • Loading branch information
Arnon Yaari committed Sep 6, 2015
1 parent 7ca207d commit 9f394c7
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions psutil/_psutil_sunos.c
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,9 @@ psutil_net_io_counters(PyObject *self, PyObject *args) {
kstat_ctl_t *kc = NULL;
kstat_t *ksp;
kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;
int ret;
int sock = -1;
struct lifreq ifr;

PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
Expand All @@ -685,25 +688,30 @@ psutil_net_io_counters(PyObject *self, PyObject *args) {
if (kc == NULL)
goto error;

sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
goto error;

ksp = kc->kc_chain;
while (ksp != NULL) {
if (ksp->ks_type != KSTAT_TYPE_NAMED)
goto next;
if (strcmp(ksp->ks_class, "net") != 0)
goto next;
/*
// XXX "lo" (localhost) interface makes kstat_data_lookup() fail
// (maybe because "ifconfig -a" says it's a virtual interface?).
if ((strcmp(ksp->ks_module, "link") != 0) &&
(strcmp(ksp->ks_module, "lo") != 0)) {
goto skip;
*/
if ((strcmp(ksp->ks_module, "link") != 0))
// skip 'lo' (localhost) because it doesn't have the statistics we need
// and it makes kstat_data_lookup() fail
if (strcmp(ksp->ks_module, "lo") == 0)
goto next;

// check if this is a network interface by sending a ioctl
strncpy(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name));
ret = ioctl(sock, SIOCGLIFFLAGS, &ifr);
if (ret == -1)
goto next;

if (kstat_read(kc, ksp, NULL) == -1) {
errno = 0;
continue;
goto next;
}

rbytes = (kstat_named_t *)kstat_data_lookup(ksp, "rbytes");
Expand Down Expand Up @@ -752,13 +760,17 @@ psutil_net_io_counters(PyObject *self, PyObject *args) {
}

kstat_close(kc);
close(sock);
return py_retdict;

error:
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (kc != NULL)
kstat_close(kc);
if (sock != -1) {
close(sock);
}
return NULL;
}

Expand Down Expand Up @@ -1138,7 +1150,7 @@ psutil_net_if_stats(PyObject* self, PyObject* args) {
kstat_t *ksp;
kstat_named_t *knp;
int ret;
int sock = 0;
int sock = -1;
int duplex;
int speed;

Expand Down Expand Up @@ -1226,7 +1238,7 @@ psutil_net_if_stats(PyObject* self, PyObject* args) {
Py_XDECREF(py_is_up);
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (sock != 0)
if (sock != -1)
close(sock);
if (kc != NULL)
kstat_close(kc);
Expand Down

0 comments on commit 9f394c7

Please sign in to comment.