Skip to content

Instantly share code, notes, and snippets.

@tonusoo
Created October 25, 2024 08:03
Show Gist options
  • Save tonusoo/0490bc5cf564689f3999f1de4eef098d to your computer and use it in GitHub Desktop.
Save tonusoo/0490bc5cf564689f3999f1de4eef098d to your computer and use it in GitHub Desktop.
netfilter mailinglist message: https://marc.info/?l=netfilter&m=172980836106595
#!/usr/bin/python3 -u
"""
-> eth0: 192.168.17.36 -> 172.16.20.3 | protocol UDP | port 6000 | DATA |
<- eth1: 10.0.0.2 -> 10.0.0.1 | protocol UDP | port 6000 | DATA |
apt install --no-install-recommends python3-pcapy python3-scapy
"""
import sys
import pcapy
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP
from scapy.sendrecv import send
def main():
interface = "eth0"
# Capture up to 65535 bytes.
#
# Pcapy does not support pcap_set_immediate_mode():
# https://github.com/helpsystems/pcapy/issues/23
# As a workaround, buffered mode with a short, 5ms read timeout is used.
#
cap = pcapy.open_live(interface, 65535, True, 5)
cap.setfilter("udp and dst port 6000")
print(f"Started to listen on {interface}")
while True:
# _pkthdr contains data like packet capture timestamp and
# capture length.
_pkthdr, frame = cap.next()
try:
eth_frame = Ether(frame)
if eth_frame.haslayer("UDP"):
udp_packet = eth_frame["UDP"]
# print(udp_packet.show(dump=True))
# Expects a route table entry for 10.0.0.1, e.g 10.0.0.2/30 on eth1.
send(IP(dst="10.0.0.1") / udp_packet, verbose=False)
except Exception as err:
print(f"Error: {err!r}")
continue
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment