Sreeju Sreedhar | e3fefd9 | 2019-04-02 15:57:15 -0700 | [diff] [blame] | 1 | |
| 2 | # Copyright 2017-present Open Networking Foundation |
| 3 | # |
| 4 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | # you may not use this file except in compliance with the License. |
| 6 | # You may obtain a copy of the License at |
| 7 | # |
| 8 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | # |
| 10 | # Unless required by applicable law or agreed to in writing, software |
| 11 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | # See the License for the specific language governing permissions and |
| 14 | # limitations under the License. |
| 15 | |
| 16 | |
| 17 | |
| 18 | """ |
| 19 | Network utilities for the OpenFlow test framework |
| 20 | """ |
| 21 | |
| 22 | ########################################################################### |
| 23 | ## ## |
| 24 | ## Promiscuous mode enable/disable ## |
| 25 | ## ## |
| 26 | ## Based on code from Scapy by Phillippe Biondi ## |
| 27 | ## ## |
| 28 | ## ## |
| 29 | ## This program is free software; you can redistribute it and/or modify it ## |
| 30 | ## under the terms of the GNU General Public License as published by the ## |
| 31 | ## Free Software Foundation; either version 2, or (at your option) any ## |
| 32 | ## later version. ## |
| 33 | ## ## |
| 34 | ## This program is distributed in the hope that it will be useful, but ## |
| 35 | ## WITHOUT ANY WARRANTY; without even the implied warranty of ## |
| 36 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## |
| 37 | ## General Public License for more details. ## |
| 38 | ## ## |
| 39 | ############################################################################# |
| 40 | |
| 41 | import socket |
| 42 | from fcntl import ioctl |
| 43 | import struct |
| 44 | |
| 45 | # From net/if_arp.h |
| 46 | ARPHDR_ETHER = 1 |
| 47 | ARPHDR_LOOPBACK = 772 |
| 48 | |
| 49 | # From bits/ioctls.h |
| 50 | SIOCGIFHWADDR = 0x8927 # Get hardware address |
| 51 | SIOCGIFINDEX = 0x8933 # name -> if_index mapping |
| 52 | |
| 53 | # From netpacket/packet.h |
| 54 | PACKET_ADD_MEMBERSHIP = 1 |
| 55 | PACKET_DROP_MEMBERSHIP = 2 |
| 56 | PACKET_MR_PROMISC = 1 |
| 57 | |
| 58 | # From bits/socket.h |
| 59 | SOL_PACKET = 263 |
| 60 | |
| 61 | def get_if(iff,cmd): |
| 62 | s=socket.socket() |
| 63 | ifreq = ioctl(s, cmd, struct.pack("16s16x",iff)) |
| 64 | s.close() |
| 65 | return ifreq |
| 66 | |
| 67 | def get_if_index(iff): |
| 68 | return int(struct.unpack("I",get_if(iff, SIOCGIFINDEX)[16:20])[0]) |
| 69 | |
| 70 | def set_promisc(s,iff,val=1): |
| 71 | mreq = struct.pack("IHH8s", get_if_index(iff), PACKET_MR_PROMISC, 0, "") |
| 72 | if val: |
| 73 | cmd = PACKET_ADD_MEMBERSHIP |
| 74 | else: |
| 75 | cmd = PACKET_DROP_MEMBERSHIP |
| 76 | s.setsockopt(SOL_PACKET, cmd, mreq) |
| 77 | |