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

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

相关文章

对Python2与Python3中__bool__方法的差异详解

学习Python面向对象编程的时候,遇到了一个很有意思的小问题。Python的__bool__方法不起作用的问题。 我反复读了我手中的教程,确认了我写的代码应该管用。可是在测试的时候却一...

python去掉字符串中重复字符的方法

复制代码 代码如下:If order does not matter, you can use "".join(set(foo))set() will create a set of u...

Python实现的单向循环链表功能示例

Python实现的单向循环链表功能示例

本文实例讲述了Python实现的单向循环链表功能。分享给大家供大家参考,具体如下: 概述: 单向循环链表是指在单链表的基础上,表的最后一个元素指向链表头结点,不再是为空。 由图可知,单...

Python获取文件ssdeep值的方法

本文实例讲述了Python获取文件ssdeep值的方法,分享给大家供大家参考。具体方法如下: 首先,得到ssdeep值,需要先import ssdeep 在ubuntu上安装pyssde...

解决Django连接db遇到的问题

解决Django连接db遇到的问题

1、django.db.utils.ConnectionDoesNotExist: The connection default doesn't exist 解决:第一个连接的命名一定...