Advertisement
ctw6avq

Sockets and structure

Jul 12th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from ctypes import *
  4. import struct
  5. import socket
  6.  
  7. host = '192.168.0.9'
  8.  
  9.  
  10. class IP(Structure):
  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_int),
  22.         ("dst", c_int)
  23.     ]
  24.  
  25.     def __init__(self, socket_buffer=None):
  26.         self.protocol_map = {1: 'ICMP', 6: 'TCP', 17: 'UDP'}
  27.  
  28.         self.src_address = socket.inet_ntoa(struct.pack('<L', self.src))
  29.         self.dst_address = socket.inet_ntoa(struct.pack('<L', self.dst))
  30.  
  31.         self.protocol = self.protocol_map[self.protocol_num]
  32.  
  33.     def __new__(cls, socket_buffer=None):
  34.         return cls.from_buffer_copy(socket_buffer)
  35.  
  36.  
  37. socket_protocol = socket.IPPROTO_UDP
  38. sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
  39. sock.bind((host, 0))
  40.  
  41. sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  42.  
  43. try:
  44.  
  45.     while True:
  46.         raw_buffer = sock.recvfrom(65565)[0]
  47.         ip_header = IP(raw_buffer[:20])
  48.         print('Protocol: {} {} -> {}'.format(ip_header.protocol, ip_header.src_address, ip_header.dst_address))
  49.  
  50. except KeyboardInterrupt:
  51.     print('\rExiting...')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement