Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created April 27, 2014 07:14
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save cslarsen/11339448 to your computer and use it in GitHub Desktop.
Save cslarsen/11339448 to your computer and use it in GitHub Desktop.
One way of sending raw Ethernet packets in Python
"""Demonstrates how to construct and send raw Ethernet packets on the
network.
You probably need root privs to be able to bind to the network interface,
e.g.:
$ sudo python sendeth.py
"""
from socket import *
def sendeth(src, dst, eth_type, payload, interface = "eth0"):
"""Send raw Ethernet packet on interface."""
assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses
assert(len(eth_type) == 2) # 16-bit ethernet type
s = socket(AF_PACKET, SOCK_RAW)
# From the docs: "For raw packet
# sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])"
s.bind((interface, 0))
return s.send(src + dst + eth_type + payload)
if __name__ == "__main__":
print("Sent %d-byte Ethernet packet on eth0" %
sendeth("\xFE\xED\xFA\xCE\xBE\xEF",
"\xFE\xED\xFA\xCE\xBE\xEF",
"\x7A\x05",
"hello"))
@nasaWelder
Copy link

@cslarsen Could I use this to talk to the internet from an air gapped computer via QR code? I have the QR two way comm figured out...

@geajack
Copy link

geajack commented Oct 19, 2018

Using code based on this I encountered this problem - when viewed in Wireshark, it seems Python is tacking some extra bytes onto the end of this "raw" data. Anyone else experiencing this?

@mpkopec
Copy link

mpkopec commented Apr 1, 2020

@geajack If you send less than Ethernet's minimum frame size it will be padded. The number is (as I remember) 60 bytes. It is actually a good sign if your packet is padded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment