Reputation: 19
I am making a port scanner using the python socket library which basically tries to connect to an IP on a port. If it is able to connect, then the port is shown open, otherwise, it displays the port as closed.
Note that this is just a basic port scanner and I am still working on it.
So, I was thinking, why don't I initiate the socket instance outside the for loop as my code is creating a new instance every time 🤔
But, when I tried it, it was saying that every port was closed
This is the snippet that I am using before the for loop -
socket_instance = socket.socket()
socket_instance.settimeout(0.5)
(I don't know about socket programming in python) Here is the main section of the code that is working properly -
def scan_ports(ip_address,port):
try:
socket_instance.connect((ip_address, port))
print("[+] Port "+str(port)+" is open")
socket_instance.close()
except:
# print("[-] Port "+str(port)+" closed")
pass
for port in range(1,501):
socket_instance = socket.socket()
socket_instance.settimeout(0.5)
scan_ports(ip_address,port)
So my question is: do I have to create a new instance of the socket function for every port?
Can't I just reuse the same instance for every port?
Upvotes: 0
Views: 30