Python使用指定端口进行http请求的例子

yipeiwu_com5年前Python基础

使用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库

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()

测试OK,可以直接在curl命令行中测试。

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设计】。

相关文章

Ubuntu16.04/树莓派Python3+opencv配置教程(分享)

无论是Windows、Linux、还是树莓派 。配置python3的opencv环境都是让人头大的一件事情,尤其是许多人用pip安装以后,发现opencv虽然装上了,但是却装在了系统原生...

Python变量类型知识点总结

Python变量类型知识点总结

变量存储在内存中的值。这就意味着在创建变量时会在内存中开辟一个空间。 基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。 因此,变量可以指定不同的数据类型,...

python 出现SyntaxError: non-keyword arg after keyword arg错误解决办法

python 出现SyntaxError: non-keyword arg after keyword arg错误解决办法 前言:     &nb...

python 统计列表中不同元素的数量方法

刚刚上网搜了一下如何用python统计列表中不同元素的数量,发现很少,找了半天。我自己来写一种方法。 代码如下 list=[1,1,2,2,3] print(list) set1=s...

python代码制作configure文件示例

在lua中,一直用lua作为config文件,或承载数据的文件 - 好处是lua本身就很好阅读,然后无需额外写解析的代码,还支持在configure文件中读环境变量,条件判断等。 在lu...