Skip to content

http sniff

python
from scapy.all import sniff, Ether


def get_tcp_items(packet, filter_ips=None):
    if packet.haslayer(Ether):
        src_mac, dst_mac = packet[Ether].src, packet[Ether].dst

        if packet.haslayer('IP'):
            src_ip, dst_ip = packet['IP'].src, packet['IP'].dst

            if any(ip in filter_ips for ip in [src_ip, dst_ip]):
                return

            if packet.haslayer('TCP'):
                src_port, dst_port = packet['TCP'].sport, packet['TCP'].dport

                src, dst = f'{src_ip}:{src_port}', f'{dst_ip}:{dst_port}'

                print('[TCP]', src, '-->', dst)
                return packet


def parse_payload(packet):
    return packet['Raw'].load


def packet_callback(packet):
    filter_ips = ['127.0.0.1']
    tcp_packet = get_tcp_items(packet, filter_ips)

    if tcp_packet:
        if tcp_packet.haslayer('Raw'):
            http_payload = parse_payload(tcp_packet)
            print(http_payload)


def main():
    iface = "Ethernet0"
    print(f'Sniffing {iface}')
    sniff(iface=iface, prn=packet_callback, store=0)


if __name__ == "__main__":
    main()

Released under the MIT License.