I have a Python script that creates many short-lived, simultaneous connections using the requests library. I specifically need to find out the source port used by each connection and I figure I need access to the underlying socket for that. Is there a way to get this through the response object?
Asked
Active
Viewed 6,635 times
11
-
An alternative could be In windows `netstat -a` can list all the processes with the ports beings used. You can code a python script to get the output of this command and then do the further work. Its not that difficult.Not sure if this can be done by the `requests` lib. – ρss Aug 31 '15 at 12:16
-
There are many short-lived simultaneous connections in my program. There is no way to know which port belongs to which connection. – Elektito Aug 31 '15 at 12:17
-
You can retrieve all the ports used by your application, but you can't use any built in command (Windows) to find which connection of your application is using which port number. I would suggest to ask in Superuser.com – ρss Aug 31 '15 at 12:56
1 Answers
13
For streaming connections (those opened with the stream=True
parameter), you can call the .raw.fileno()
method on the response object to get an open file descriptor.
You can use the socket.fromfd(...)
method to create a Python socket object from the descriptor:
>>> import requests
>>> import socket
>>> r = requests.get('http://google.com/', stream=True)
>>> s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)
>>> s.getpeername()
('74.125.226.49', 80)
>>> s.getsockname()
('192.168.1.60', 41323)
For non-streaming sockets, the file descriptor is cleaned up before the response object is returned. As far as I can tell there's no way to get it in this situation.

larsks
- 277,717
- 41
- 399
- 399
-
6This works great. I found out that if I use your method inside the "response" callback I can do this even with non-streaming requests. – Elektito Sep 01 '15 at 05:03