473,796 Members | 2,532 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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('ath 0')
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('foo bar')
Out[3]:
{'addr': '104.154.165.18 3',
'brdaddr': '104.154.165.18 3',
'hwaddr': '00:00:68:9a:a5 :b7',
'netmask': '104.154.165.18 3'}

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 4893
On Mar 3, 3:38 pm, Bart Van Loon <bbb...@inGen.b ewrote:
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('25 6s', ifname[:15])
info = fcntl.ioctl(soc k.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(h ex(ord(char))[2:])
return ':'.join(hwaddr )
else:
return socket.inet_nto a(info[20:24])

def ifconfig(ifname ):
ifreq = {'ifname': ifname}
infos = {}
osys = platform.system ()
sock = socket.socket(s ocket.AF_INET, socket.SOCK_DGR AM)
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('ad dr'):
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...@gma il.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('25 6s', ifname[:15])
info = fcntl.ioctl(soc k.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(h ex(ord(char))[2:])
return ':'.join(hwaddr )
else:
return socket.inet_nto a(info[20:24])

def ifconfig(ifname ):
ifreq = {'ifname': ifname}
sock = socket.socket(s ocket.AF_INET, socket.SOCK_DGR AM)
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('25 6s', ifname[:15])
info = fcntl.ioctl(soc k.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(h ex(ord(char))[2:])
return ':'.join(hwaddr )
else:
return socket.inet_nto a(info[20:24])

def ifconfig(ifname ):
ifreq = {'ifname': ifname}
sock = socket.socket(s ocket.AF_INET, socket.SOCK_DGR AM)
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.25 5', '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_ParseTupl e(args, "s", &itf)) {
PyErr_SetString (PyExc_Exceptio n, "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_method s[] = {
{"ipaddr", (PyCFunction)ip addr, METH_VARARGS, "ipaddr(string) \n"},
{NULL, NULL, 0, NULL}
};

DL_EXPORT(void) initifconfig(vo id)
{
Py_InitModule3( "ifconfig", ifconfig_method s, "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
5384
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
13979
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 encap:Ethernet HWaddr 10:EE:0C:36:8E:C8 inet addr:192.168.11.22 Bcast:192.168.11.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:41816612 errors:0 dropped:0 overruns:0 frame:0
0
1414
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 file /etc/resolv.conf with the good nameserver IP. So, it it works and my network is up. My problem is that when I use the function socket.gethostbyaddr just after setting up the network and without getting out of my script, I get an exception...
131
6230
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 portable C code - *not only* because, in a 'C sense', I
0
1247
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 requirement that the host computer has .net or a jre installed. I also am not very fond of developing with VC++ *cry*. Also done some perl, so I checked out ruby, python, python.... hey
0
3693
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 suggestion... For Example fconfig eth0 eth0 Link encap:Ethernet HWaddr 00:13:D3:3F:7F:37 inet addr:172.16.170.117 Bcast:172.16.170.255 Mask:255.255.255.0 inet6 addr: fe80::213:d3ff:fe3f:7f37/64 Scope:Link <- here...
0
1815
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 to get the mac address which i can get by connecting to the remote machine and by executing ifconfig command. Now to connect to a remote machine in python i tried using pexpect module by which i can ssh to remote machine and get the mac...
8
8950
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 company provides me a common IPv4 address. I'd like to set up my workstation (Windows XP or Linux Debian, doesn't really matter) to temporarily use IPv6 for trying to add such feature to my library (I work on both Windows XP and Linux). Could...
6
2608
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 portable. It needs to have an underlying file descriptor/file handle, as it will be passed to non python code. Is there a portable /dev/null somewhere in the standard library?
0
9527
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10223
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9050
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.