Extract received data in a tcp socket in Python

前端 未结 1 1843
暗喜
暗喜 2020-12-20 10:28

I have a client sending a packet with a custom layer \"Reservation\" created with Scapy

Client.py

#!/usr/bin/env python

import sock         


        
相关标签:
1条回答
  • 2020-12-20 11:03

    You can use s=str(packet) to serialize a packet in scapy 2 and packet=Layer(s) to force deserialization of a bytestream as Layer.

    In your case:

    rdata = sock.recv(8192)
    layer = Reservation(rdata)
    layer.show()
    print layer.id
    

    Note that you can also bind your layer for scapys autodissect/payload guessing with bind_layers() to make it work with sniff() or dissection of tcp/Reservation bytestreams (tcp packet with reservation payload). The following line binds TCP.dport=5005 to Reservation.

    bind_layers(TCP, Reservation, dport=5005)
    

    update: specific answer to your question.

    You do not have to care about the IP/TCP layer as this is all handled within the socket. The data that is received by socket.recv is the payload to TCP therefore all you have to do is to force scapy to deserialize the received data as Reservation.

    TCP Socket:

    data=[]
    while True:
        chunk = conn.recv(BUFFER_SIZE)
        if not chunk: 
            break
        print "received data:", chunk
        data.append(chunk)
    layer = Reservation(''.join(data))
    layer.show()
    print layer.id
    

    Additionally, you can instruct scapy to try to auto-dissect your layer based on a simple rule e.g. TCP.dport==5005 with a call to bind_layers(). This way it will also work with sniff or whenever you receive the full IP/TCP/Reservation/Raw bytestream.

    Raw Socket:

    bind_layers(TCP, Reservation, dport=5005) # bind Reservation as nextlayer to TCP.dport=5005
    # ...
    data, peer = s.recvfrom(BUFFER_SIZE)
    print "received data:", peer, repr(data)
    layer = IP(data)                # dissection automagic based on rules registered with bind_layers
    layer.show()
    print layer[Reservation].id
    
    0 讨论(0)
提交回复
热议问题