Here is the answer to a similar question that I prepared earlier .... much earlier ... Socket usage error when reusing sockets
The error is different, but the main problem is probably the same: you consume all available ports and try to reuse them before the TIME_WAIT state has ended.
[EDIT: in response to comments]
If this is the application / specification for your application, one obvious strategy is to control the connection speed to avoid this situation.
Alternatively, you can use the httplib module. httplib.HTTPConnection() allows you to specify the source_address tuple, with which you can specify the port from which you can connect, for example. this will connect to localhost: 1234 from localhost: 9999:
import httplib conn = httplib.HTTPConnection('localhost:1234', source_address=('localhost',9999)) conn.request('GET', '/index.html')
Then it is a matter of controlling the assignment of the source port, as described in my earlier answer. If you are on Windows, you can use this method to bypass the default port range of 1024-5000.
There is (of course) an upper limit on how many connections you are going to make, and it is doubtful which application would require a quick connection to thousands of connections.
source share