Welcome, guest | Sign In | My Account | Store | Cart

This code shows how to call the low-level POSIX interface of Python, and handle the return values with the struct module.

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#! /usr/bin/env python
import fcntl, struct, sys
from socket import *

# set some symbolic constants
SIOCGIFFLAGS = 0x8913
null256 = '\0'*256

# get the interface name from the command line 
ifname = sys.argv[1]

# create a socket so we have a handle to query
s = socket(AF_INET, SOCK_DGRAM)

# call ioctl() to get the flags for the given interface
result = fcntl.ioctl(s.fileno(), SIOCGIFFLAGS, ifname + null256)

# extract the interface's flags from the return value
flags, = struct.unpack('H', result[16:18])

# check "UP" bit and print a message
up = flags & 1
print ('DOWN', 'UP')[up]

# return a value suitable for shell's "if"
sys.exit(not up)

To really understand how the code works, you need to take a look into the system includes, on Linux the necessary definitions are located in "/usr/include/linux/if.h".

Though this code is certainly more complex than the "classical" approach, which would be calling "/sbin/ifconfig" and parsing its output, you get two positive effects in return: directly using the system calls avoids the major overhead of spawning a new process for such a simple query, and you are not dependant on the output format of "ifconfig" which might change over time or from system to system and break your code.

1 comment

Mark Rowe 19 years, 4 months ago  # | flag

Query whether interface is up on Mac OS X. The above code works fine on Mac OS X, with one small exception. The value of SIOCGIFFLAGS is 0xc0206911. This would imply to me that this method is not as portable as it seems.