通过中的特定网络发送http请求

2024-05-23 20:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个网络接口(wifi和以太网)都可以上网。假设我的接口是eth(以太网)和wlp2(wifi)。我需要特定的请求通过eth接口,其他请求通过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,但是如果没有任何方法可以使用pycurl或{},那么我可以使用requests。在

How to specify source interface in python requests module?引用Requests, bind to an ip,它不起作用。在


Tags: toipcomhttpurlrequestpostrequests
2条回答

尝试将内部IP(192.168.0.200)更改为下面代码中相应的iface。在

import requests
from requests_toolbelt.adapters import source

def check_ip(inet_addr):
    s = requests.Session()
    iface = source.SourceAddressAdapter(inet_addr)
    s.mount('http://', iface)
    s.mount('https://', iface)
    url = 'https://emapp.cc/get_my_ip'
    resp = s.get(url)
    print(resp.text)

if __name__ == '__main__':
    check_ip('192.168.0.200')

我找到了一种使用pycurl的方法。这很有魅力。在

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给出答案。在

相关问题 更多 >