I want to build a packet sniffer in python that is able to sniff packets, analyze them and in a second step inject packets on a local interface.
I have found an example that I had to tweak a bit to work. My working version looks like this:
from pprint import pprint
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
s.bind(("192.168.1.100", 0))
#s.socketopt(socket.IPPOROT_IP, socket.IP_HDRINCL, 1)
#s.ioct(socket.SIO_RCVALL, socket.RCVALL_ON)
i = 5
while i > 0:
data = s.recvfrom(10000)
pprint(data)
i -= 1
The output I get looks like this:
(b'E\x00\x008\x05>\x00\x00@\x06\xf1c\xc0\xa8\x01j\xc0\xa8\x01d\x10\x00#*'
b'\xe25\xfc\x00\x00\x00\x00\x00\x90\x02\x11\x1c\x8cQ\x00\x00\x02\x04\x05\xb4'
b'\x08\n\x00Q,\xd2\x00\x00\x00\x00\x00\x00',
('192.168.1.106', 0))
(b'E\x00\x008\x05?\x00\x00@\x06\xf1b\xc0\xa8\x01j\xc0\xa8\x01d\x10\x01#*'
b'\xd0\x03\x9a\x00\x00\x00\x00\x00\x90\x02\x11\x1c\x00o\x00\x00'
b'\x02\x04\x05\xb4\x08\n\x00Q,\xe6\x00\x00\x00\x00\x00\x00',
('192.168.1.106', 0))
(b'E\x00\x008\x05@\x00\x00@\x06\xf1a\xc0\xa8\x01j\xc0\xa8\x01d\x10\x02#*'
b'\xa5\xd18\x00\x00\x00\x00\x00\x90\x02\x11\x1c\x8c\x8c\x00\x00'
b'\x02\x04\x05\xb4\x08\n\x00Q,\xfa\x00\x00\x00\x00\x00\x00',
('192.168.1.106', 0))
(b'E\x00\x008\x05A\x00\x00@\x06\xf1`\xc0\xa8\x01j\xc0\xa8\x01d\x10\x03#*'
b'\x96\x9e\xd6\x00\x00\x00\x00\x00\x90\x02\x11\x1c\xfd\xa9\x00\x00'
b'\x02\x04\x05\xb4\x08\n\x00Q-\x0e\x00\x00\x00\x00\x00\x00',
('192.168.1.106', 0))
(b'E\x00\x008\x05B\x00\x00@\x06\xf1_\xc0\xa8\x01j\xc0\xa8\x01d\x10\x04#*'
b'\xa9\xb0\xfe\x00\x00\x00\x00\x00\x90\x02\x11\x1c\xc2\x82\x00\x00'
b'\x02\x04\x05\xb4\x08\n\x00Q-"\x00\x00\x00\x00\x00\x00',
('192.168.1.106', 0))
The output confused me quite a bit and I am not sure how to use it. I expected a byte array but in the multiple arrays there are several characters that I do not expect there, like E, >, @, #, and so on. I tried to find out what they mean but I was not able to get any information that explains how it is to be used. I want to parse information from the TCP part and analyze them but I cannot make any progress on this.
If someone could explain to me what exactly the format of the byte array is and what each of the components mean that would be very helpful!
Many thanks in advance for any kind of help!
Kevin's comment helped me in solving my problem:
This is the code that works for me. It does not feel like a clean solution but it works. If someone knows a proper way how to print the actual bytes without converting them, I would appreciate knowing that as well.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
s.bind(("192.168.1.100", 0))
i = 5
while i > 0:
data = s.recvfrom(10000)
print("b'{}'".format(''.join(' {:02x}'.format(b) for b in data[0])))
i -= 1