Harman5007

decode_ip

Jun 18th, 2020
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 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. socket_protocol = socket.IPPROTO_ICMP
  43. sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
  44. sniffer.bind((host, 0))
  45. sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  46.  
  47. try:
  48. while True:
  49. # read in a packet
  50. raw_buffer = sniffer.recvfrom(65565)[0]
  51.  
  52. # create an IP header from the first 20 bytes of the buffer
  53. ip_header = IP(raw_buffer[:20])
  54.  
  55. # print out the protocol that was detected and the hosts
  56. print(f"Protocol: {ip_header.protocol}, {ip_header.src_address} -> {ip_header.dst_address} ")
  57.  
  58. # handle CTRL-C
  59. except KeyboardInterrupt:
  60. sys.exit(1)
Add Comment
Please, Sign In to add comment