I have recently been introduced to the threading module in python so I decided to play around with it I opened a python socket server on port 7000:
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('127.0.0.1',7000))
s.listen(1)
c, a = s.accept()
and made my client server try connecting to every port from 1 to 65535 until it establishes connection on port 7000. Obviously this would take very long so I multi-threaded it:
import threading
import socket
import sys
host = None
def conn(port):
try:
s.connect((host,port))
print 'Connected'
sys.exit(1)
except:
pass
global host
host = '127.0.0.1'
for i in range(65535):
t = threading.Thread(target=conn, args=(i,))
t.start()
When the client connects its suppose to return the message 'connected' however when debugging I noticed some very strange behavior with the program. Sometimes the program would return that it connected, other times the program would fail to output that it was connected to the server instead it would just terminate without printing anything.
Its obviously a problem with the threads. As when i make the client connect to port 7000 only it works 100% of the time. However threading it through all 65535 ports causes the client to sometimes not print anything. What is the reason for this and how can I prevent or circumvent it.
Edit: I realized making it try to connect to a smaller number of ports, ports 1-10 and port 7000, gives it a higher chance of printing out connected.