Advertisement
Guest User

Untitled

a guest
Aug 30th, 2015
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. import socket
  2.  
  3. import os
  4. import struct
  5. from ctypes import *
  6.  
  7.  
  8.  
  9. # host to listen on
  10. host = "192.168.16.128"
  11.  
  12. # IP header
  13. class IP(Structure):
  14.     # map C datataypes to IP header values
  15.     _fields_ = [
  16.         ("ihl",          c_ubyte, 4),
  17.         ("version",      c_ubyte, 4),
  18.         ("tos",          c_ubyte),
  19.         ("len",          c_ushort),
  20.         ("id",           c_ushort),
  21.         ("offset",       c_ushort),
  22.         ("ttl",          c_ubyte),
  23.         ("protocol_num", c_ubyte),
  24.         ("sum",          c_ushort),
  25.         ("src",          c_ulong),
  26.         ("dst",          c_ulong)
  27.     ]
  28.  
  29.     def __new__(self, socket_buffer=None):
  30.         return self.from_buffer_copy(socket_buffer)
  31.  
  32.     def __init__(self, socket_buffer=None):
  33.  
  34.         # map protocol constants to their names
  35.         self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"}
  36.  
  37.         # human readable IP addresses
  38.         self.src_address = socket.inet_ntoa(struct.pack("<L",self.src))
  39.         self.dst_address = socket.inet_ntoa(struct.pack("<L",self.dst))
  40.  
  41.         # human readable protocol
  42.         try:
  43.             self.protocol = self.protocol_map[self.protocol_num]
  44.         except:
  45.             self.protocol = str(self.protocol_num)
  46.  
  47. if os.name == "nt":
  48.     socket_protocol = socket.IPPROTO_IP
  49. else:
  50.     socket_protocol = socket.IPPROTO_ICMP
  51.  
  52. sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
  53.  
  54. sniffer.bind((host, 0))
  55. sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  56.  
  57. if os.name == "nt":
  58.     sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
  59.  
  60. try:
  61.     while True:
  62.  
  63.         # read in packet
  64.         raw_buffer = sniffer.recvfrom(6556)[0]
  65.  
  66.         # create IP header from first 20 bytes of buffer
  67.         ip_header = IP(raw_buffer[0:20])
  68.  
  69.         # print out protocol that was detected + hosts
  70.         print "Protocol: %s %s -> %s" % (ip_header.protocol, ip_header.src_address, ip_header.dst_address)
  71.  
  72. # CTRL-C
  73. except:
  74.  
  75.     # if Windows, turn off promiscuous mode
  76.     if os.name == "nt":
  77.         sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement