Example of Python making http requests using a specified port

  • 2021-07-26 08:18:42
  • OfStack

Using the requests library


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

I tested with wireshark and found that it was on port 54321.

Using the pycurl library


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

To test OK, you can test it directly from the curl command line.


curl --local-port 12520 http://baidu.com

Reference

https://stackoverflow.com/questions/47202790/python-requests-how-to-specify-port-for-outgoing-traffic?rq=1


Related articles: