问题
Environment :Win10, python 3.7 and scapy 2.4.3
路由表如下所示, ZeroTier是一个虚拟内网接口,I219是外网接口。 明显I219的Metric比较小,所以I219应该是默认网卡,scapy 的 conf.iface 返回的也是I219,但 get_working_if() 却返回了 ZeroTier。
>>> conf.route
Network Netmask Gateway Iface Output IP Metric
0.0.0.0 0.0.0.0 25.255.255.254 ZeroTier One Virtual Port 172.28.33.102 10034
0.0.0.0 0.0.0.0 10.11.91.254 Intel(R) Ethernet Connection (5) I219-V 10.11.91.161 25
>>> conf.iface
<NetworkInterface [Intel(R) Ethernet Connection (5) I219-V]>
>>> get_working_if()
<NetworkInterface [ZeroTier One Virtual Port]>
分析原因,源代码中get_working_if() 是获取的conf.route中mask最小的网卡。如果有多个网卡的mask是0.0.0.0,
就有可能出错。conf.iface初始化情况下是获取的默认路由对应的网卡,但scapy中多处代码均有conf.iface = get_working_if(),因此在scapy执行过程中conf.iface可能会被改写,且sr(),traceroute()等多个函数如果不指定iface的话就会提示网卡不可用。已在github上提交此issue
/Lib/site-packages/scapy/arch/windows/init.py
def get_working_if():
"""Return an interface that works"""
try:
# return the interface associated with the route with smallest
# mask (route by default if it exists)
iface = min(conf.route.routes, key=lambda x: x[1])[3] // 我觉得这里应该改成lambda x: x[5] ,1代表mask,5代表metric
解决方案
根据scapy作者的回复,get_working_if() 并不是用来返回默认网卡,而是用来返回一个可以用的网卡。
The return value of get_working_if() does not seem “wrong”. As I said, it is not supposed to return the default interface but rather “an interface that works”.
如果要获取默认网卡,应该使用conf.route.resync() ; conf.route.route('0.0.0.0')[0]
两个步骤
For the first, you need to run conf.route.resync() to read again the interfaces and routes from your host network stack.
For the second, conf.route.route(‘0.0.0.0’) returns the route (as a Python tuple) for 0.0.0.0, so you can use conf.route.route(‘0.0.0.0’)[0] to get the interface.