使用requests库classSourcePortAdapter(HTTPAdapter):""""Transportadapter"thatallowsustosetthesourceport."""def__init__(
使用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 指定端口 http请求