Zsolt Haraszti | 91350eb | 2016-11-05 15:33:53 -0700 | [diff] [blame] | 1 | """ |
| 2 | Network utilities for the OpenFlow test framework |
| 3 | """ |
| 4 | |
| 5 | ########################################################################### |
| 6 | ## ## |
| 7 | ## Promiscuous mode enable/disable ## |
| 8 | ## ## |
| 9 | ## Based on code from Scapy by Phillippe Biondi ## |
| 10 | ## ## |
| 11 | ## ## |
| 12 | ## This program is free software; you can redistribute it and/or modify it ## |
| 13 | ## under the terms of the GNU General Public License as published by the ## |
| 14 | ## Free Software Foundation; either version 2, or (at your option) any ## |
| 15 | ## later version. ## |
| 16 | ## ## |
| 17 | ## This program is distributed in the hope that it will be useful, but ## |
| 18 | ## WITHOUT ANY WARRANTY; without even the implied warranty of ## |
| 19 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## |
| 20 | ## General Public License for more details. ## |
| 21 | ## ## |
| 22 | ############################################################################# |
| 23 | |
| 24 | import socket |
| 25 | from fcntl import ioctl |
| 26 | import struct |
| 27 | |
| 28 | # From net/if_arp.h |
| 29 | ARPHDR_ETHER = 1 |
| 30 | ARPHDR_LOOPBACK = 772 |
| 31 | |
| 32 | # From bits/ioctls.h |
| 33 | SIOCGIFHWADDR = 0x8927 # Get hardware address |
| 34 | SIOCGIFINDEX = 0x8933 # name -> if_index mapping |
| 35 | |
| 36 | # From netpacket/packet.h |
| 37 | PACKET_ADD_MEMBERSHIP = 1 |
| 38 | PACKET_DROP_MEMBERSHIP = 2 |
| 39 | PACKET_MR_PROMISC = 1 |
| 40 | |
| 41 | # From bits/socket.h |
| 42 | SOL_PACKET = 263 |
| 43 | |
| 44 | def get_if(iff,cmd): |
| 45 | s=socket.socket() |
| 46 | ifreq = ioctl(s, cmd, struct.pack("16s16x",iff)) |
| 47 | s.close() |
| 48 | return ifreq |
| 49 | |
| 50 | def get_if_index(iff): |
| 51 | return int(struct.unpack("I",get_if(iff, SIOCGIFINDEX)[16:20])[0]) |
| 52 | |
| 53 | def set_promisc(s,iff,val=1): |
| 54 | mreq = struct.pack("IHH8s", get_if_index(iff), PACKET_MR_PROMISC, 0, "") |
| 55 | if val: |
| 56 | cmd = PACKET_ADD_MEMBERSHIP |
| 57 | else: |
| 58 | cmd = PACKET_DROP_MEMBERSHIP |
| 59 | s.setsockopt(SOL_PACKET, cmd, mreq) |
| 60 | |