Search code examples
pythonlinuxnetwork-programmingpacket

Writing raw IP data to an interface (linux)


I have a file which contains raw IP packets in binary form. The data in the file contains a full IP header, TCP\UDP header, and data. I would like to use any language (preferably python) to read this file and dump the data onto the line.

In Linux I know you can write to some devices directly (echo "DATA" > /dev/device_handle). Would using python to do an open on /dev/eth1 achieve the same effect (i.e. could I do echo "DATA" > /dev/eth1)


Solution

  • Something like:

    #!/usr/bin/env python
    import socket
    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
    s.bind(("ethX", 0))
    
    blocksize = 100;
    with open('filename.txt') as fh:
        while True:
            block = fh.read(blocksize)
            if block == "": break  #EOF
            s.send(block)
    

    Should work, haven't tested it however.

    • ethX needs to be changed to your interface (e.g. eth1, eth2, wlan1, etc.)
    • You may want to play around with blocksize. 100 bytes at a time should be fine, you may consider going up but I'd stay below the 1500 byte Ethernet PDU.
    • It's possible you'll need root/sudoer permissions for this. I've needed them before when reading from a raw socket, never tried simply writing to one.
    • This is provided that you literally have the packet (and only the packet) dumped to file. Not in any sort of encoding (e.g. hex) either. If a byte is 0x30 it should be '0' in your text file, not "0x30", "30" or anything like that. If this is not the case you'll need to replace the while loop with some processing, but the send is still the same.
    • Since I just read that you're trying to send IP packets -- In this case, it's also likely that you need to build the entire packet at once, and then push that to the socket. The simple while loop won't be sufficient.