如何在Python请求中指定源IP地址

发布于 2025-02-11 00:41:00 字数 269 浏览 2 评论 0原文

我在网络接口卡上配置了几个IP地址。我需要指定通过哪个IP地址python 请求必须连接到Web服务器。是否可以?

import requests
r = requests.get("http://example.com/foo/bar")

我需要强制requests.get通过划定的IP地址执行HTTP请求。

还有其他http库在Python中支持此功能吗?

I have several IP addresses configured on my network interface card. I need to specify through which IP address python requests must connect to the web server. Is it possible?

import requests
r = requests.get("http://example.com/foo/bar")

I need to force requests.get to perform http request through a dasignated IP address.

Is there any other http library that support this feature in python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我不咬妳我踢妳 2025-02-18 00:41:01

您可以使用 sourceaddressadapter 来自Respections-toolbelt:sourceaddressadapter

import requests
from requests_toolbelt.adapters import source

source = source.SourceAddressAdapter('127.0.0.1')

with requests.Session() as session:
    session.mount('http://', source)
    r = session.get("http://example.com/foo/bar")

You can use a SourceAddressAdapter from requests-toolbelt:

import requests
from requests_toolbelt.adapters import source

source = source.SourceAddressAdapter('127.0.0.1')

with requests.Session() as session:
    session.mount('http://', source)
    r = session.get("http://example.com/foo/bar")
离鸿 2025-02-18 00:41:01

您是否正在运行Django/Django-Rest项目?因为,如果是这样,您只需在python manage.py runserver命令中指定自定义主机和端口!喜欢:

python manage.py runserver 0.0.0.0:8001

希望我理解问题

Are you running a Django/Django-Rest project? Because, if so, you can just specify a custom host and port into the python manage.py runserver command! Like so:

python manage.py runserver 0.0.0.0:8001

Hope I understood the problem

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文