8fe9788b2f86edcdf1f9b0e4eb8571e35947dac5
[openblackhole/openblackhole-enigma2.git] / lib / python / Components / Netlink.py
1 # Listen to hotplug events. Can be used to listen for hotplug events and
2 # similar things, like network connections being (un)plugged.
3 import os
4 import socket
5
6 class NetlinkSocket(socket.socket):
7         def __init__(self):
8                 NETLINK_KOBJECT_UEVENT = 15 # hasn't landed in socket yet, see linux/netlink.h
9                 socket.socket.__init__(self, socket.AF_NETLINK, socket.SOCK_DGRAM, NETLINK_KOBJECT_UEVENT)
10                 self.bind((os.getpid(), -1))
11
12         def parse(self):
13                 data = self.recv(512)
14                 event = {}
15                 for item in data.split('\x00'):
16                         if not item:
17                                 # terminator
18                                 yield event
19                                 event = {}
20                         else:
21                                 try:
22                                         k,v = item.split('=', 1)
23                                         event[k] = v
24                                 except:
25                                         event[None] = item
26
27 # Quick unit test (you can run this on any Linux machine)
28 if __name__ == '__main__':
29         nls = NetlinkSocket()
30         print "socket no:", nls.fileno()
31         while 1:
32                 for item in nls.parse():
33                         print repr(item)