2 * Extension to gather information about network interfaces
4 * Mark Huang <mlhuang@cs.princeton.edu>
5 * Copyright (C) 2006 The Trustees of Princeton University
16 #include <sys/types.h>
17 #include <sys/socket.h>
20 #include <sys/ioctl.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
27 #include <net/if_arp.h>
30 #include <net/ethernet.h>
33 gifconf(PyObject *self, PyObject *args)
41 struct sockaddr_in *sin;
43 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
44 return PyErr_SetFromErrno(PyExc_OSError);
46 len = sizeof(struct ifreq);
52 buf = realloc(ifc.ifc_req, len);
57 if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
59 } while (ifc.ifc_len >= len);
63 addrs = Py_BuildValue("{}");
65 for (ifr = ifc.ifc_req, len = ifc.ifc_len; len > 0; ifr++, len -= sizeof(struct ifreq)) {
66 sin = (struct sockaddr_in *) &ifr->ifr_addr;
68 Py_BuildValue("s", ifr->ifr_name),
69 Py_BuildValue("s", inet_ntoa(sin->sin_addr)));
79 gifaddr(PyObject *self, PyObject *args)
84 struct sockaddr_in *sin;
86 if (!PyArg_ParseTuple(args, "s", &name))
89 memset(&ifr, 0, sizeof(ifr));
90 strncpy(ifr.ifr_name, name, IFNAMSIZ);
92 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
93 return PyErr_SetFromErrno(PyExc_OSError);
95 if (ioctl(s, SIOCGIFADDR, &ifr) < 0) {
97 return PyErr_SetFromErrno(PyExc_OSError);
102 sin = (struct sockaddr_in *) &ifr.ifr_addr;
103 return Py_BuildValue("s", inet_ntoa(sin->sin_addr));
107 gifhwaddr(PyObject *self, PyObject *args)
112 char mac[sizeof(ifr.ifr_hwaddr.sa_data) * 3], *c;
115 if (!PyArg_ParseTuple(args, "s", &name))
118 memset(&ifr, 0, sizeof(ifr));
119 strncpy(ifr.ifr_name, name, IFNAMSIZ);
121 if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
122 return PyErr_SetFromErrno(PyExc_OSError);
124 if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0) {
126 return PyErr_SetFromErrno(PyExc_OSError);
131 switch (ifr.ifr_hwaddr.sa_family) {
136 len = sizeof(ifr.ifr_hwaddr.sa_data);
140 for (i = 0, c = mac; i < len; i++) {
142 c += sprintf(c, ":");
143 c += sprintf(c, "%02X", (unsigned char)(ifr.ifr_hwaddr.sa_data[i] & 0xFF));
146 return Py_BuildValue("s", mac);
149 static PyMethodDef methods[] = {
150 { "gifconf", gifconf, METH_VARARGS, "Get all interface addresses" },
151 { "gifaddr", gifaddr, METH_VARARGS, "Get interface address" },
152 { "gifhwaddr", gifhwaddr, METH_VARARGS, "Get interface hardware address" },
153 { NULL, NULL, 0, NULL }
159 Py_InitModule("sioc", methods);