3

I need to read a complete (raw) IP frame from a TCP stream socket using Python. Essentially I want an unmodified frame just as if it came off the physical line, including all the header information.

I have been looking into raw sockets in Python but I have ran into some issues. I don't need to form my own packets, I simply need to read and forward them verbatim.

So, how can I read an entire IP frame (incl. header) from an existing TCP socket (in Python)?

Preferably I'd like to use only standard libraries. Also, I am on a Linux host.

Thanks!

3
  • 6
    You can't "read an entire IP frame from a TCP socket" (no matter what language). TCP sockets don't provide access to raw packets. You will probably need to use a packet sniffing interface. Commented Mar 23, 2011 at 19:23
  • So what if I created a TCP server, is it possible to create a raw socket connected to the TCP port? Either way, I think I am going with a packet sniffing interface as suggested. Commented Mar 23, 2011 at 19:47
  • A raw socket has no "port" semantics! In your TCP server, the socket is created on a layer above the network's. All of the data it receives is stripped from the lower level layers by the OS already. The only way to get them is by sniffing raw packets and determine the type/port and other upper-level semantics yourself (or via some library). Commented Mar 24, 2011 at 1:25

3 Answers 3

3

If you don't mind using Scapy, which is not part of the standard library, and super speed isn't a requirement, you can use its sniff function. It takes a callback. Something like:

pkts_rxd = []
def process_and_send(pkt):
    pkts_rxd.append(pkt)
    sendp(pkt, 'eth1')
sniff(prn=process_and_send, iface='eth0', count=100)

You can run the sniff in a different thread or process, with count=0 and stick the received packets on a queue if you want it to run forever. Just make sure that you put str(pkt) on the queue. I've seen weird things happen when putting scapy packets on multiprocessing.Queues.

Debian and Ubuntu both have Scapy in their apt repositories. I don't know about rpm distros. It's pretty easy to install from source though: ./setup.py install.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, this was definitely the way to go. Thanks for the tip!
0

You should try scapy.

Comments

0

Maybe pylibpcap can do that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.