Skip to content

Instantly share code, notes, and snippets.

@fqrouter
Created February 11, 2013 06:39
Show Gist options
  • Select an option

  • Save fqrouter/4753011 to your computer and use it in GitHub Desktop.

Select an option

Save fqrouter/4753011 to your computer and use it in GitHub Desktop.
class L2Sniffer(threading.Thread):
def __init__(self, iface, src, dst, no_filter=False):
super(L2Sniffer, self).__init__()
self.daemon = True
self.no_filter = no_filter
self.iface = iface
self.src = src
self.dst = dst
self.started = threading.Event()
self.started.clear()
self.should_stop = False
self.packets = []
def run(self):
try:
if self.no_filter:
filter = None # for PPP link
else:
filter = '(dst host %s and src host %s) or icmp' % (self.src, self.dst)
with contextlib.closing(conf.L2listen(iface=self.iface, filter=filter)) as l2_listen_socket:
self.started.set()
while True:
result = select.select([l2_listen_socket], [], [], 0.1)
if l2_listen_socket not in result[0]:
if self.should_stop:
return # no data and should stop => stop
continue
packet = l2_listen_socket.recv()
if IP in packet:
packet = packet[IP]
else:
continue
self.collect_packet(packet)
except:
traceback.print_exc()
def start_sniffing(self):
self.start()
self.started.wait()
def stop_sniffing(self):
self.should_stop = True
self.join()
return self.packets
def collect_packet(self, packet):
packet.mark = None
if self.dst == packet.src and self.src == packet.dst:
packet.mark = 'inbound'
self.packets.append(packet)
elif IPerror in packet:
if self.src == packet[IPerror].src and self.dst == packet[IPerror].dst:
packet.mark = 'ttl-exceeded'
self.packets.append(packet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment