AndAsh
AndAsh

Reputation: 21

How to capture data from a TCP socket with scapy

I am creating a TCP socket:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_sock:
    server_sock.bind((HOST, PORT))
    server_sock.listen()

    while True:
        sock, addr = server_sock.accept()

Then I want to use scapy to capture packets from the socket. Right now, I'm doing it like this:

data = sniff(iface = 'eth0', filter=f“port {PORT}”, count = 1)

I receive one packet and send it to the queue. In a parallel process, I take packets from the queue and process them.

I am receiving packets from a network interface using a socket port filter. Is there any way to receive packets using sniff directly from the socket?

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_sock:
    server_sock.bind((HOST, PORT))
    server_sock.listen()

    while True:
        sock, addr = server_sock.accept()
        while True:
           data = sniff(iface = 'eth0', filter=f“port {PORT}”, count = 1)

Upvotes: 1

Views: 31

Answers (1)

Cukic0d
Cukic0d

Reputation: 5421

Typically, if the protocol above TCP is HTTP for instance, you would do

from scapy.supersocket import StreamSocket
[...]

while True:
    sock, addr = server_sock.accept()
    sock = StreamSocket(sock, HTTP)
    sock.sniff(...)

If it's something else, you'd have to replace HTTP in the above example.

Upvotes: 0

Related Questions