From 88fd54bc54d5f9aad20abcfb0cdca74b21605dea Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Fri, 17 Apr 2020 19:35:11 +0500 Subject: [PATCH] Parse IP header (src, dst) --- main.py | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index a297043..8e4a789 100755 --- a/main.py +++ b/main.py @@ -1,6 +1,27 @@ #!/usr/bin/env python3 import pytun +import struct +import ipaddress + +class IpHeader: + def __init__(self, raw): + self.ver_ihl, \ + self.tos, \ + self.total_length, \ + self.ident, \ + self.flags_fragoffset, \ + self.ttl, \ + self.proto, \ + self.chksum, \ + src, \ + dst, \ + self.opt1, \ + self.opt2, \ + self.pad = struct.unpack('>BBHHHBBHIIHBB', raw) + + self.src = ipaddress.IPv4Address(src) + self.dst = ipaddress.IPv4Address(dst) def main(): tun_iface = pytun.TunTapDevice() @@ -16,7 +37,18 @@ def main(): while True: buf = tun_iface.read(tun_iface.mtu) - print(buf) + + flags = buf[:2] + proto = buf[2:4] + + if proto != b'\x08\x00': + continue + + ip_header = IpHeader(buf[4:28]) + body = buf[28:] + + print(ip_header.src, '→', ip_header.dst, 'len: %d' % ip_header.total_length) + if __name__ == '__main__': main()