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

相关文章

python中enumerate函数用法实例分析

本文实例讲述了python中enumerate函数用法。分享给大家供大家参考。具体分析如下: 今日发现一个新函数 enumerate 。一般情况下对一个列表或数组既要遍历索引又要遍历元素...

python实现图书借阅系统

本文实例为大家分享了python实现图书借阅系统的具体代码,供大家参考,具体内容如下 部分代码: from flask import Flask,render_template fr...

python 字典操作提取key,value的方法

python 字典操作提取key,value的方法

python 字典操作提取key,value dictionaryName[key] = value 1.为字典增加一项 2.访问字典中的值 3、删除字典中的一项...

Python内置函数OCT详解

英文文档: 复制代码 代码如下:oct ( x ) Convert an integer number to an octal string. The result is a valid...

Python时间的精准正则匹配方法分析

本文实例讲述了Python时间的精准正则匹配方法。分享给大家供大家参考,具体如下: 要用正则表达式精准匹配时间,其实并不容易 方式一: >>> import re...