通过特定网络接口发送http请求 [英] Send http request through specific network interface
问题描述
我有两个网络接口(wifi 和以太网)都可以访问互联网.假设我的接口是 eth
(以太网)和 wlp2
(wifi).我需要通过 eth
接口和其他通过 wpl2
的特定请求.
I have two network interfaces (wifi and ethernet) both with internet access. Let's say my interfaces are eth
(ethernet) and wlp2
(wifi). I need specific requests to go through eth
interface and others through wpl2
.
类似于:
// Through "eth"
request.post(url="http://myapi.com/store_ip", iface="eth")
// Through "wlp2"
request.post(url="http://myapi.com/log", iface="wlp2")
我正在使用 requests
,但如果没有任何方法可以使用 或
urllib
,我可以使用 pycurl
或 urllib
>请求代码>.
I'm using requests
, but I can use pycurl
or urllib
if there isn't any way to do it with requests
.
如何在python请求模块中指定源接口? 指的是 请求,绑定到 ip 并且它不起作用.
How to specify source interface in python requests module? refers to Requests, bind to an ip and it doesn't work.
推荐答案
我找到了一种使用 pycurl
的方法.这就像一个魅力.
I found a way using pycurl
. This works like a charm.
import pycurl
from io import BytesIO
import json
def curl_post(url, data, iface=None):
c = pycurl.Curl()
buffer = BytesIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.POST, True)
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json'])
c.setopt(pycurl.TIMEOUT, 10)
c.setopt(pycurl.WRITEFUNCTION, buffer.write)
c.setopt(pycurl.POSTFIELDS, data)
if iface:
c.setopt(pycurl.INTERFACE, iface)
c.perform()
# Json response
resp = buffer.getvalue().decode('UTF-8')
# Check response is a JSON if not there was an error
try:
resp = json.loads(resp)
except json.decoder.JSONDecodeError:
pass
buffer.close()
c.close()
return resp
if __name__ == '__main__':
dat = {"id": 52, "configuration": [{"eno1": {"address": "192.168.1.1"}}]}
res = curl_post("http://127.0.0.1:5000/network_configuration/", json.dumps(dat), "wlp2")
print(res)
我将问题悬而未决,希望有人可以使用 requests
给出答案.
I'm leaving the question opened hopping that someone can give an answer using requests
.
这篇关于通过特定网络接口发送http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!