Python: Add Promiscuous Mode To Interface

So.. I started programming in python this weekend. I’ve touched on it before but never really gave it a fair chance. I was looking for a while on how to set an interface into promiscuous mode for some arp spoofing tool that i’m creating and while searching couldn’t really find anything….

so here is my little snippet for anyone looking to do the same thing:

import socket;
import struct;
import fcntl;

SIOCGIFFLAGS = 0x8913;
SIOCSIFFLAGS = 0x8914;
IFF_PROMISC = 0x100;

current_flags = 0;

sd = socket.socket(socket.PF_PACKET, socket.SOCK_RAW);

# This will return the current flags present on the interface
ifreq = fcntl.ioctl(sd, SIOCGIFFLAGS, “eth0” + “” * 256);

# extract current flags field from struct returned
(current_flags,) = struct.unpack(“16xH”, ifreq[:18]);

# add the Promisc flag
current_flags |= IFF_PROMISC;

# create the new struct for setting the interface flags
ifreq = struct.pack(“4s12xH”, “eth0”, current_flags);

# call ioctl() to update the flags for the interface
fcntl.ioctl(sd, SIOCSIFFLAGS, ifreq);

# Turn off the IFF_PROMISC flag
current_flags ^= IFF_PROMISC;
ifreq = struct.pack(“4s12xH”, “eth0”, current_flags);

# remove the Promisc flag from the interface once done
fcntl.ioctl(sd, SIOCSIFFLAGS, ifreq);

If you think of any other ways to do the above in a more ‘clean’ format, please leave a comment as I would love to know how.

Advertisements