It was Sun, 4 Mar 2007 02:38:58 +0500, when Bart Van Loon wrote: > Hi all, > > I'm looking for a portable (FreeBSD and Linux) way of getting typical > ifconfig information into Python.
After lots of trial and error (I'm proficient in C at all), I puzzled togehter the following. It works (at least on FreeBSD and Linux), but is still fairly rough, as it returns an empty string when given a non existing or down interface. I'll clean it up in due time. :-) #include "Python.h" #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <stdio.h> #include <ifaddrs.h> #include <string.h> // parameters: string (interface name) // output: string (ip address of interface in decimal notation) PyObject * ipaddr(PyObject *self, PyObject *args) { char ip[ 200 ]; char *itf; if (! PyArg_ParseTuple(args, "s", &itf)) { PyErr_SetString(PyExc_Exception, "no interface given!"); return NULL; } struct ifaddrs *ifa = NULL, *ifp = NULL; if (getifaddrs (&ifp) < 0) { perror ("getifaddrs"); return NULL; } for (ifa = ifp; ifa; ifa = ifa->ifa_next) { socklen_t salen; if (ifa->ifa_addr->sa_family == AF_INET) salen = sizeof (struct sockaddr_in); else if (ifa->ifa_addr->sa_family == AF_INET6) salen = sizeof (struct sockaddr_in6); else continue; if (strncmp(ifa->ifa_name, itf, sizeof(itf))) { continue; } if (getnameinfo (ifa->ifa_addr, salen, ip, sizeof (ip), NULL, 0, NI_NUMERICHOST) < 0) { perror ("getnameinfo"); continue; } break; } freeifaddrs (ifp); return Py_BuildValue("s", ip); } static PyMethodDef ifconfig_methods[] = { {"ipaddr", (PyCFunction)ipaddr, METH_VARARGS, "ipaddr(string)\n"}, {NULL, NULL, 0, NULL} }; DL_EXPORT(void) initifconfig(void) { Py_InitModule3("ifconfig", ifconfig_methods, "Provides a function to get an ip address of a certain interface.\n"); } Inspiration came from and credit goes to the author of http://www.hungry.com/~alves/local-ip-in-C.html -- regards, BBBart Hobbes : How is the diorama coming along? Calvin : I'm almost finished. Hobbes : I don't see the roadrunner. Weren't you going to put one in? Calvin : See the cotton balls I glued down? Hobbes : Yeah? Calvin : The roadrunner just ran out of the scene leaving behind clouds of dust! -- http://mail.python.org/mailman/listinfo/python-list