首页 > 编程 > Python > 正文

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

2019-11-25 12:13:56
字体:
来源:转载
供稿:网友

使用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请求的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表