From 60a82ce9620e8a49edb91f690ca09bc50c2b1833 Mon Sep 17 00:00:00 2001 From: Guillaume Valadon Date: Thu, 27 Jun 2019 12:31:11 +0200 Subject: [PATCH] Smarter interface selection when sending one packet --- scapy/sendrecv.py | 16 ++++++++++++++++ test/linux.uts | 12 ++++++++++++ 2 files changed, 28 insertions(+) diff --git a/scapy/sendrecv.py b/scapy/sendrecv.py index 2e358c7fe3a..c9b6a791f87 100644 --- a/scapy/sendrecv.py +++ b/scapy/sendrecv.py @@ -462,9 +462,25 @@ def sr(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): return result +def _interface_selection(iface, packet): + """ + Select the network interface according to the layer 3 destination + """ + + if iface is None: + try: + iff = packet.route()[0] + except AttributeError: + iff = None + return iff or conf.iface + + return iface + + @conf.commands.register def sr1(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): """Send packets at layer 3 and return only the first answer""" + iface = _interface_selection(iface, x) s = conf.L3socket(promisc=promisc, filter=filter, nofilter=nofilter, iface=iface) ans, _ = sndrcv(s, x, *args, **kargs) diff --git a/test/linux.uts b/test/linux.uts index 75a2f6f8386..6de875f066f 100644 --- a/test/linux.uts +++ b/test/linux.uts @@ -366,3 +366,15 @@ saved_conf_prog_tcpdump = conf.prog.tcpdump conf.prog.tcpdump = "does_not_exist" assert _check_tcpdump() == False conf.prog.tcpdump = saved_conf_prog_tcpdump + += Test _interface_selection +~ netaccess linux needs_root + +import os +from scapy.sendrecv import _interface_selection +assert _interface_selection(None, IP(dst="8.8.8.8")/UDP()) == conf.iface +exit_status = os.system("ip link add name scapy0 type dummy") +exit_status = os.system("ip addr add 192.0.2.1/24 dev scapy0") +exit_status = os.system("ip link set scapy0 up") +assert _interface_selection(None, IP(dst="192.0.2.42")/UDP()) == "scapy0" +exit_status = os.system("ip link del name dev scapy0")