Get 'ifconfig' information via Python
mal at lemburg.com
Wed Aug 4 12:20:48 CEST 1999
David N. Welton wrote:
> So, I think I'm getting close...
> import fcntl
> import IN
> import struct
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> res = fcntl.ioctl(s, IN.SIOCSIFHWADDR, ??????)
> I can't seem to find what goes in ?????.
> Is this the right way to be doing things? I suppose I can always go
> pull apart the sources for ifconfig itself, and make a .so that does
> what I need, but I get the feeling that I can do what I need from
> within Python.
> Yeah, I could popen ifconfig, too, but that's ugly.
> Downloading python sources now to see what I can see in the fcntl
The .ioctl() function can take a string or an integer as
third argument. To find out what to pass for a given option,
look at man ioctl and man ioctl_list. The exact meaning is
not mentioned there unfortunately, though.
On Linux, just dig into the net/core/dev.c file to find out
what happens for the above option:
The argument is being interpreted as struct ifreq and then copied
if(securelevel > 0)
The basic ifreq struct is defined in include/linux/if.h:
* Interface request structure used for socket
* ioctl's. All interface ioctl's must have parameter
* definitions which begin with ifr_name. The
* remainder may be interface specific.
#define IFHWADDRLEN 6
#define IFNAMSIZ 16
char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" *
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
struct ifmap ifru_map;
char ifru_slave[IFNAMSIZ]; /* Just fits the size */
#define ifr_name ifr_ifrn.ifrn_name /* interface name */
#define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */
#define ifr_addr ifr_ifru.ifru_addr /* address */
#define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-p lnk */
#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */
#define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */
#define ifr_flags ifr_ifru.ifru_flags /* flags */
#define ifr_metric ifr_ifru.ifru_metric /* metric */
#define ifr_mtu ifr_ifru.ifru_mtu /* mtu */
#define ifr_map ifr_ifru.ifru_map /* device map */
#define ifr_slave ifr_ifru.ifru_slave /* slave device */
#define ifr_data ifr_ifru.ifru_data /* for use by interface */
Building these structs can be done using the Python struct
module... playing around with this can probably crash your system
In the end, I think you're better off hacking together a
new extension module.
Hope that helps.
Y2000: 149 days left
Python Pages: http://www.lemburg.com/python/
More information about the Python-list