Skip to content

Smarter interface selection when sending one packet #2108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions scapy/sendrecv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions test/linux.uts
Original file line number Diff line number Diff line change
Expand Up @@ -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")