PycURL 通过特定接口发送 DNS 流量

PycURL send DNS traffic through particular interface

我的盒子上有多个接口,我想使用 python 强制流量通过特定接口。

answers how to do that for HTTP traffic. But when I look at tcpdump, the DNS queries do not honor the interface setting. libcurl provides options to force DNS traffic through a particular interface using option CURLOPT_DNS_INTERFACE and CURLOPT_DNS_LOCAL_IP4

我尝试通过 C 使用相同的方法,当 libcurl 是使用 c-ares 支持构建时,它似乎支持接口。

但是当从 pycurl 版本使用相同的选项时会导致以下错误:

AttributeError: DNS_INTERFACE
AttributeError: DNS_LOCAL_IP4

我正在尝试建议的猴子补丁on this thread。但是根据评论,其他人已经报告说它不起作用。谢谢

[edit] 用 bind 测试了上面提到的 monkey-patching,tcpdump 仍然显示通过不同接口的流量。固定格式。

发生 AttributeError 是因为 PycURL 只支持它在 src/module.c 中列出的 curl 选项。可以通过镜像它支持 CURLOPT_INTERFACE 的方式来添加对 CURLOPT_DNS_INTERFACE 的支持——通过添加

    insint_c(d, "DNS_INTERFACE", CURLOPT_DNS_INTERFACE);

    case CURLOPT_DNS_INTERFACE:

在 src/module.c 和 src/easyopt.c 中关于 CURLOPT_INTERFACE 的行之后,我可以构建一个支持 DNS_INTERFACE 的版本。我使用 python setup.py install 进行构建(参见 docs), running into two errors that were solved with this answer and make src/docstrings.c (see GitHub)。

这里是 docs 中添加了 DNS_INTERFACE 的示例:

import pycurl
from StringIO import StringIO

buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'http://pycurl.io/')
c.setopt(c.WRITEDATA, buffer)
c.setopt(c.DNS_INTERFACE, "enp9s0")
c.perform()
c.close()

body = buffer.getvalue()
print(body)

它目前在 c.setopt(c.DNS_INTERFACE, "enp9s0") 上给了我 pycurl.error: (4, ''),但是这个错误 likely 不会发生在你身上,因为你构建了支持 c-ares 的 libcurl。