473,399 Members | 3,401 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

portable Python ifconfig

Hi all,

I'm looking for a portable (FreeBSD and Linux) way of getting typical
ifconfig information into Python.

Some research on the web brought me to Linux only solutions

http://aspn.activestate.com/ASPN/Coo.../Recipe/439094
http://aspn.activestate.com/ASPN/Coo.../Recipe/439093

which I didn't manage to port to FreeBSD (I'm not that experienced).
Finally though, I found out about pyifconfig:

http://mail.python.org/pipermail/pyt...st/009274.html

which compiles fine on Linux after changing <python1.5/Python.hto
<python2.4/Python.h>. On FreeBSD there is no SIOCGIFHWADDR, so I
just commented out that part.

I can now do

In [1]: from pyifconfig import pyifconfig

In [2]: pyifconfig('ath0')
Out[2]:
{'addr': '192.168.50.104',
'brdaddr': '192.168.50.255',
'hwaddr': '00:17:f2:4c:a5:0c',
'netmask': '255.255.255.0'}

on Linux, and

In [1]: from pyifconfig import pyifconfig

In [2]: pyifconfig('vr1')
Out[2]:
{'addr': '192.168.50.1',
'brdaddr': '192.168.50.255',
'hwaddr': '\xff\xff',
'netmask': '255.255.255.0'}

on FreeBSD.

The problem now is that I get seemingly random information when I pass a
non-existing interface, a down interface or an empty string to
pyifconfig, which is very hard to figure out from inside a script:

In [3]: pyifconfig('foobar')
Out[3]:
{'addr': '104.154.165.183',
'brdaddr': '104.154.165.183',
'hwaddr': '00:00:68:9a:a5:b7',
'netmask': '104.154.165.183'}

so, any pointers here on how I can go on from this point?

any help is appreciated

--
regards,
BBBart

Wormwood : Calvin, how about you?
Calvin : Hard to say ma'am. I think my cerebellum just fused.
Mar 3 '07 #1
6 4857
On Mar 3, 3:38 pm, Bart Van Loon <bbb...@inGen.bewrote:
I'm looking for a portable (FreeBSD and Linux) way of getting typical
ifconfig information into Python.
Here's a pure python version of the C extension, based on the recipes
you posted. In this version, the 'addr' key will not exist for a non-
existent / non-active interface.

import socket, fcntl, struct, platform

def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
info = fcntl.ioctl(sock.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(hex(ord(char))[2:])
return ':'.join(hwaddr)
else:
return socket.inet_ntoa(info[20:24])

def ifconfig(ifname):
ifreq = {'ifname': ifname}
infos = {}
osys = platform.system()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if osys == 'Linux':
# offsets defined in /usr/include/linux/sockios.h on linux 2.6
infos['addr'] = 0x8915 # SIOCGIFADDR
infos['brdaddr'] = 0x8919 # SIOCGIFBRDADDR
infos['hwaddr'] = 0x8927 # SIOCSIFHWADDR
infos['netmask'] = 0x891b # SIOCGIFNETMASK
elif 'BSD' in osys: # ???
infos['addr'] = 0x8915
infos['brdaddr'] = 0x8919
infos['hwaddr'] = 0x8927
infos['netmask'] = 0x891b
try:
for k,v in infos.items():
ifreq[k] = _ifinfo(sock, v, ifname)
except:
pass
sock.close()
return ifreq

ifc = ifconfig('ath0')
if ifc.has_key('addr'):
print ifc

I'm pretty sure the offsets would be different for BSD, but I don't
have any BSD boxes to test on (looks like from a bit of googling that
you might need to look at /compat/linux/linux_ioctl.h for the offsets
on BSDs). I'll leave it to you to fill in the BSD stuff.

Regards,
Jordan

Mar 4 '07 #2
On Mar 3, 7:17 pm, "MonkeeSage" <MonkeeS...@gmail.comwrote:
I'm pretty sure the offsets would be different for BSD
Then again, mabye not.

http://freebsd.active-venture.com/Fr...x_ioctl.h.html

Regards,
Jordan

Mar 4 '07 #3
Bart,

Can you try this and let us know if it works for FreeBSD?

import socket, fcntl, struct

def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
info = fcntl.ioctl(sock.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(hex(ord(char))[2:])
return ':'.join(hwaddr)
else:
return socket.inet_ntoa(info[20:24])

def ifconfig(ifname):
ifreq = {'ifname': ifname}
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ifreq['addr'] = _ifinfo(sock, 0x8915, ifname) # SIOCGIFADDR
ifreq['brdaddr'] = _ifinfo(sock, 0x8919, ifname) #
SIOCGIFBRDADDR
ifreq['netmask'] = _ifinfo(sock, 0x891b, ifname) #
SIOCGIFNETMASK
ifreq['hwaddr'] = _ifinfo(sock, 0x8927, ifname) #
SIOCSIFHWADDR
except:
pass
sock.close()
return ifreq

Regards,
Jordan

Mar 4 '07 #4
It was 3 Mar 2007 18:43:57 -0800, when MonkeeSage wrote:
Bart,

Can you try this and let us know if it works for FreeBSD?
thanks for you suggestions!
import socket, fcntl, struct

def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
info = fcntl.ioctl(sock.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(hex(ord(char))[2:])
return ':'.join(hwaddr)
else:
return socket.inet_ntoa(info[20:24])

def ifconfig(ifname):
ifreq = {'ifname': ifname}
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ifreq['addr'] = _ifinfo(sock, 0x8915, ifname) # SIOCGIFADDR
ifreq['brdaddr'] = _ifinfo(sock, 0x8919, ifname) #
SIOCGIFBRDADDR
ifreq['netmask'] = _ifinfo(sock, 0x891b, ifname) #
SIOCGIFNETMASK
ifreq['hwaddr'] = _ifinfo(sock, 0x8927, ifname) #
SIOCSIFHWADDR
except:
pass
sock.close()
return ifreq
apparenlty, it doesn't. :-(

I changes the except block into

except Exception, e:
print e

and added

if __name__ == '__main__':
print ifconfig('ng0')
print ifconfig('vr0')
print ifconfig('vr2')
print ifconfig('xl0')

ng0 exists and has an IP (virtual interface created by mpd)
vr0 exists but does not have an IP (phisical interface for mpd)
vr2 exists and has an IP configured
xl0 does not exist

output:

[Errno 25] Inappropriate ioctl for device
{'ifname': 'ng0'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'vr0'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'vr2'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'xl0'}

however, in Linux I get the following results:

[Errno 99] Cannot assign requested address
{'ifname': 'eth0'}
{'hwaddr': '0:17:f2:4c:a5:c', 'ifname': 'ath0', 'netmask': '255.255.255.0', 'addr': '192.168.50.104', 'brdaddr': '192.168.50.255'}
{'hwaddr': '0:0:0:0:0:0', 'ifname': 'tun0', 'netmask': '255.255.255.255', 'addr': '192.168.3.6', 'brdaddr': '0.0.0.0'}
[Errno 19] No such device
{'ifname': 'wielewoele'}

which seems 100% correct.

--
regards,
BBBart

Susie: You'd get a good grade without doing any work.
Calvin: So?
Susie: It's wrong to get rewards you haven't earned.
Calvin: I've never heard of anyone who couldn't live with that.
Mar 4 '07 #5
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!
Mar 4 '07 #6
It was Sun, 4 Mar 2007 14:09:20 +0500, when Bart Van Loon wrote:
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
err... I'm NOT proficient in c at all :-)

--
groetjes,
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!
Mar 4 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: olivier Ravard | last post by:
Hi, I want to know the MAC address of my local network card with a python script. I tested the socket module which gives only the IP address. Is someone have an idea ? Thanks. O.R.
1
by: Roman Mashak | last post by:
Hello, All! I just started to learn Perl, and don't know exactly what regexp I can use to get IP address from 'ifconfig' routine. My system is linux, so output is the following: eth0 Link...
0
by: HIL | last post by:
Hi everybody, I wrote a python script to setup my network interface under Linux. To perform it, I use directly from my python script external programs as 'ifconfig' and 'route' ans I fill the...
131
by: pemo | last post by:
Is C really portable? And, apologies, but this is possibly a little OT? In c.l.c we often see 'not portable' comments, but I wonder just how portable C apps really are. I don't write...
0
by: Andreas | last post by:
Hi Group, I want to get into writing portable apps that can run solely off a USB stick, but I have a few problems. I'm originally a java/.net developer, but I don't want it to be a...
0
by: prabina | last post by:
hi all, I have faced one problem in ifconfig in linux.I used ifconfig command then after i want delete the IPV6 address permanetly by ifconfig up/down, how is it possible plz give me some...
0
vinoj
by: vinoj | last post by:
Hi All, These are the following things which i want to do:- 1. I will be taking the ipaddress, username and password from the user using cgi ffrom the browser. 2. Now i want...
8
by: Giampaolo Rodola' | last post by:
I'm not sure if this is a question about python programming, system administration or sockets in general... I have the FTP server in my signature to which I'd want to add IPv6 support. My hosting...
6
by: Brendan Miller | last post by:
Hi, I have functions that take a file object and write to it. In some cases I just want to throw out what is written to that file object. I want something like open('/dev/null', 'w'), but...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.