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