blob: f53c2e04869939961daeb81dc22e711a250f8b67 [file] [log] [blame]
Dan Talaycoe37999f2010-02-09 15:27:12 -08001#!/usr/bin/env python
2
3"""
4Network utilities for the OpenFlow controller
5"""
6
Dan Talayco19dbc792010-02-12 23:00:54 -08007###########################################################################
8## ##
9## Promiscuous mode enable/disable ##
10## ##
11## Based on code from Scapy by Phillippe Biondi ##
12## ##
13## ##
14## This program is free software; you can redistribute it and/or modify it ##
15## under the terms of the GNU General Public License as published by the ##
16## Free Software Foundation; either version 2, or (at your option) any ##
17## later version. ##
18## ##
19## This program is distributed in the hope that it will be useful, but ##
20## WITHOUT ANY WARRANTY; without even the implied warranty of ##
21## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ##
22## General Public License for more details. ##
23## ##
24#############################################################################
25
Dan Talaycoe37999f2010-02-09 15:27:12 -080026import socket
Dan Talayco19dbc792010-02-12 23:00:54 -080027from fcntl import ioctl
28import struct
Dan Talaycoe37999f2010-02-09 15:27:12 -080029
Dan Talayco19dbc792010-02-12 23:00:54 -080030# From net/if_arp.h
31ARPHDR_ETHER = 1
32ARPHDR_LOOPBACK = 772
Dan Talaycoe37999f2010-02-09 15:27:12 -080033
Dan Talayco19dbc792010-02-12 23:00:54 -080034# From bits/ioctls.h
35SIOCGIFHWADDR = 0x8927 # Get hardware address
36SIOCGIFINDEX = 0x8933 # name -> if_index mapping
Dan Talaycoe37999f2010-02-09 15:27:12 -080037
Dan Talayco19dbc792010-02-12 23:00:54 -080038# From netpacket/packet.h
39PACKET_ADD_MEMBERSHIP = 1
40PACKET_MR_PROMISC = 1
Dan Talaycoe37999f2010-02-09 15:27:12 -080041
Dan Talayco19dbc792010-02-12 23:00:54 -080042# From bits/socket.h
43SOL_PACKET = 263
Dan Talaycoe37999f2010-02-09 15:27:12 -080044
Dan Talayco19dbc792010-02-12 23:00:54 -080045def get_if(iff,cmd):
46 s=socket.socket()
47 ifreq = ioctl(s, cmd, struct.pack("16s16x",iff))
48 s.close()
49 return ifreq
Dan Talaycoe37999f2010-02-09 15:27:12 -080050
Dan Talayco19dbc792010-02-12 23:00:54 -080051def get_if_hwaddr(iff):
52 addrfamily, mac = struct.unpack("16xh6s8x",get_if(iff,SIOCGIFHWADDR))
53 if addrfamily in [ARPHDR_ETHER,ARPHDR_LOOPBACK]:
54 return str2mac(mac)
55 else:
56 raise Exception("Unsupported address family (%i)"%addrfamily)
Dan Talaycoe37999f2010-02-09 15:27:12 -080057
Dan Talayco19dbc792010-02-12 23:00:54 -080058def get_if_index(iff):
59 return int(struct.unpack("I",get_if(iff, SIOCGIFINDEX)[16:20])[0])
60
61def set_promisc(s,iff,val=1):
62 mreq = struct.pack("IHH8s", get_if_index(iff), PACKET_MR_PROMISC, 0, "")
63 if val:
64 cmd = PACKET_ADD_MEMBERSHIP
65 else:
66 cmd = PACKET_DROP_MEMBERSHIP
67 s.setsockopt(SOL_PACKET, cmd, mreq)
68