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