johnmahugu

python sniffer ip header decode

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