You are not logged in.

#1 2010-08-11 20:15:26

jerryluc
Member
From: Norway
Registered: 2008-05-20
Posts: 95

Python and the socket module

Can someone show me how to use the socket module to:
- bring a network interface up/down
- fetch amount of bytes downloaded/uploaded

thanks...

Offline

#2 2010-08-15 08:13:37

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Python and the socket module

Yeah, sure. This is how I get IP and hardware addresses. There is a method to get each interface name via sockets, but I prefer parsing "/proc/net/dev" only because it gives me the full list, either up or down. The socket method will only give you what's up.

def getIntIPv4(name):
    s    = socket(AF_INET,SOCK_DGRAM)
    addr    = lambda op: inet_ntoa(ioctl(s.fileno(),op,
          struct.pack("256s",name))[20:24])

    try:    return {
        "addr"    : addr(0x8915),
        "mask"    : addr(0x891b),
        "bcast"    : addr(0x8919),
        "state"    : "up"
        }
    except: return {
        "addr"    : "0.0.0.0",
        "mask"    : "255.255.255.255",
        "bcast"    : "255.255.255.255",
        "state"    : "down"
        }

def getIntHWAddr(name):
    s    = socket(AF_INET,SOCK_DGRAM)
    return    {
        "hwaddr": ":".join([hex(ord(c))[2:].zfill(2) for c in
        ioctl(s.fileno(),0x8927,struct.pack("256s",name))[18:24]])
    }

def getInterfaces():
    f    = open("/proc/net/dev","r")
    data    = [l.split(":") for l in f.readlines()[2:]]; f.close()
    temp    = None
    out    = []

    for name,stats in [[n.strip(),s.split()] for n,s in data]:
        temp = {
        "name"        : name,
        "rx-bytes"    : stats[0],
        "rx-packets"    : stats[1],
        "tx-bytes"    : stats[8],
        "tx-packets"    : stats[9]
        }
        temp.update(getIntHWAddr(name))
        temp.update(getIntIPv4(name))
        out.append(temp)

    return sorted(out,key=lambda i:i["name"])

As far as controlling their state, I know you can with root privileges and the right offsets but I'd have to look them up. I'll post back if I can find an example for that.

Edit: Here's how you get "up" interfaces using sockets: http://coderstalk.blogspot.com/2010/02/ … using.html

Last edited by GraveyardPC (2010-08-18 00:35:20)

Offline

#3 2010-08-18 00:35:38

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Python and the socket module

Bump: So I kept thinking about this, it's an interesting question. I did some research and found the right offsets SIOCGIFFLAGS (0x8913) and SIOCSIFFLAGS (0x8914) in "/usr/include/linux/sockios.h". Then I grabbed the flags from "if.h" and used them like this:

from socket import *
from fcntl import ioctl
import struct

SIOCGIFFLAGS    = 0x8913
SIOCSIFFLAGS    = 0x8914

# Flags
IFF_UP          = 0x1
IFF_BROADCAST   = 0x2
IFF_DEBUG       = 0x4
IFF_LOOPBACK    = 0x8
IFF_POINTOPOINT = 0x10
IFF_NOTRAILERS  = 0x20
IFF_RUNNING     = 0x40
IFF_NOARP       = 0x80
IFF_PROMISC     = 0x100
IFF_ALLMULTI    = 0x200
IFF_MASTER      = 0x400
IFF_SLAVE       = 0x800
IFF_MULTICAST   = 0x1000
IFF_PORTSEL     = 0x2000
IFF_AUTOMEDIA   = 0x4000
IFF_DYNAMIC     = 0x8000
IFF_LOWER_UP    = 0x10000
IFF_DORMANT     = 0x20000
IFF_ECHO        = 0x40000

def getIntFlags(name):
        s       = socket(AF_INET,SOCK_DGRAM)
        ret     = ioctl(s.fileno(),SIOCGIFFLAGS,struct.pack("18s",name))
        flags   = struct.unpack("16sh",ret)[1]
        return    flags

def setIntFlags(name,flags):
        s       = socket(AF_INET,SOCK_DGRAM)
        return    ioctl(s.fileno(),SIOCSIFFLAGS,struct.pack("16sh",name,flags))

# Get State (1=up, 0=down):
print getIntFlags("eth0") & IFF_UP

# Set State (goes up if down, down if up):
setIntFlags("eth0",getIntFlags("eth0")+IFF_UP)

Remember, for setIntFlags you will need privileged access. You can use the previous code to find an interface name list so you can use these functions. But I can't find a way to get the RX and TX info with sockets, I'd just parse "/proc/net/dev" for that.

Last edited by GraveyardPC (2010-08-18 02:26:45)

Offline

Board footer

Powered by FluxBB