pythonwiresharkpyshark

Reading TCP packets to and from a specific port in Python 3


I am trying to replicate the data I am seeing in Wireshark using this filter tcp.port == 25565. I have tried using socket and pyshark, however, I cannot seem to find a simple tutorial which explains how to do this.

As you can probably tell by the port, I am trying to decode Minecraft packets. Advice on how to get the payload and get a start on parsing that data would be very helpful.

So far, I have this code:

from scapy.all import *

def test(pkt):
    print(pkt)

if __name__ == '__main__':
    single = sniff(filter="tcp.port == 25565", prn=test)

Any help is greatly appreciated.


Solution

  • You want sniff(filter="tcp port 25565", prn=test).

    Look at the scapy documentation.

    We can add filtering to capture only packets that are interesting to us. Use standard tcpdump/libpcap syntax:

    That syntax is specified in the pcap-filter man page.

    qualifiers restrict the match to a particular protocol.
    Possible protos are: ether, fddi, tr, wlan, ip, ip6, arp, rarp, decnet, tcp and udp. E.g., 'ether src foo', 'arp net 128.3', 'tcp port 21',

    I don't think the syntax is well explained in it (or I'm not reading the right part), but as you can see, tcp port 21 is a valid filter and what you're looking for. For an alternative syntax that uses an and, you'll see this further down:

    Primitives may be combined using: A parenthesized group of primitives and operators (parentheses are special to the Shell and must be escaped).
    Negation ('!' or 'not').
    Concatenation ('&&' or 'and').
    Alternation ('||' or 'or').

    As you can see, your filter options (or primitives) should be grouped using an operator. In this case, you want both to be true, so you want tcp and port 25565, or alternatively, tcp && port 25565.