Harman5007

decode_icmp

Jun 19th, 2020
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. import socket
  2. import sys
  3. import os
  4. import struct
  5. from ctypes import *
  6.  
  7. # host to listen on
  8. host = "192.168.43.162"
  9.  
  10. # our IP header
  11. class IP(Structure):
  12. _fields_ = [
  13. ("ihl", c_ubyte, 4),
  14. ("version", c_ubyte, 4),
  15. ("tos", c_ubyte),
  16. ("len",c_ushort),
  17. ("id", c_ushort),
  18. ("offset", c_ushort),
  19. ("ttl",c_ubyte),
  20. ("protocol_num",c_ubyte),
  21. ("sum", c_ushort),
  22. ("src", c_uint32),
  23. ("dst", c_uint32)
  24. ]
  25.  
  26. def __new__(self, socket_buffer=None):
  27. return self.from_buffer_copy(socket_buffer)
  28. def __init__(self, socket_buffer=None):
  29. # map protocol constants to their names
  30. self.protocol_map = {1:"ICMP", 6:"TCP", 17:"UDP"}
  31.  
  32. # human readable IP addresses
  33. self.src_address = socket.inet_ntoa(struct.pack("@I",self.src))
  34. self.dst_address = socket.inet_ntoa(struct.pack("@I",self.dst))
  35.  
  36. # human readable protocol
  37. try:
  38. self.protocol = self.protocol_map[self.protocol_num]
  39. except:
  40. self.protocol = str(self.protocol_num)
  41.  
  42. class ICMP(Structure):
  43. _fields_ = [
  44. ("type", c_ubyte),
  45. ("code", c_ubyte),
  46. ("checksum", c_ushort),
  47. ("unused", c_ushort),
  48. ("next_hop_mtu", c_ushort)
  49. ]
  50.  
  51. def __new__(self, socket_buffer):
  52. return self.from_buffer_copy(socket_buffer)
  53. def __init__(self, socket_buffer):
  54. pass
  55.  
  56. socket_protocol = socket.IPPROTO_ICMP
  57. sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
  58. sniffer.bind((host, 0))
  59. sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  60.  
  61. try:
  62. while True:
  63. # read in a packet
  64. raw_buffer = sniffer.recvfrom(65565)[0]
  65.  
  66. # create an IP header from the first 20 bytes of the buffer
  67. ip_header = IP(raw_buffer[:20])
  68.  
  69. header_length = ip_header.ihl * 4
  70. data = raw_buffer[header_length:]
  71.  
  72. # print out the protocol that was detected and the hosts
  73. print(f"Protocol: {ip_header.protocol}, {ip_header.src_address} -> {ip_header.dst_address} ")
  74.  
  75. # if it's ICMP, we want it
  76. if ip_header.protocol == "ICMP":
  77. # calculate where our ICMP packet starts
  78. offset = ip_header.ihl * 4
  79. #buf = raw_buffer[offset:offset + sizeof(ICMP)]
  80. buf = data[:sizeof(ICMP)]
  81.  
  82. # create our ICMP structure
  83. icmp_header = ICMP(buf)
  84.  
  85. print(f"ICMP -> Type:{icmp_header.type}, Code:{icmp_header.code}" )
  86. print()
  87.  
  88. # handle CTRL-C
  89. except KeyboardInterrupt:
  90. sys.exit(1)
Add Comment
Please, Sign In to add comment