Python指定端口发起HTTP请求的两种实现方案

林见深
林见深
发布时间:2026-10-13| 5人浏览过
原创

本文介绍了在Python中通过指定源端口发起HTTP请求的两种方法。首先,通过继承requests库的HTTPAdapter自定义适配器,实现指定源端口(如54321)的功能,并配合Wiresh抓包验证。其次,演示使用pycurl库设置LOCALPORT参数实现相同效果。文章提供了完整的代码示例及curl命令行测试方法,适用于需要固定出口端口的网络场景。

使用requests库指定源端口

在Python中,若需通过指定源端口发起HTTP请求,可借助requests库进行定制开发。


class SourcePortAdapter(HTTPAdapter):
 """"Transport adapter" that allows us to set the source port."""

 def __init__(self, port, *args, **kwargs):
  self.poolmanager = None
  self._source_port = port
  super().__init__(*args, **kwargs)

 def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
  self.poolmanager = PoolManager(
   num_pools=connections, maxsize=maxsize,
   block=block, source_address=('', self._source_port))

s = requests.Session()
s.mount('https://baidu.com', SourcePortAdapter(54321))
s.get('https://baidu.com')

经Wireshark抓包测试,确认请求确实从指定的54321端口发出。

使用pycurl库指定源端口

另一种方案是使用pycurl库,该库原生支持源端口设置。


c = pycurl.Curl()
c.setopt(c.URL, 'https://curl.haxx.se/dev/')
c.setopt(c.LOCALPORT, 54321)
c.setopt(c.LOCALPORTRANGE, [52314,56321,5532])
c.perform()
c.close()

经测试功能正常,用户也可直接在curl命令行中使用--local-port参数进行验证。


curl --local-port 12520 http://baidu.com

参考资源

https://stackoverflow.com/questions/47202790/python-requests-how-to-specify-port-for-outgoing-traffic?rq=1

以上关于Python使用指定端口进行HTTP请求的示例内容分享完毕,希望能为读者提供有效参考,并欢迎继续支持本站获取更多技术资讯。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。