Port Scanner in Python

Python is a great tool to do some socket operations. I have written a piece of code by which I can scan a port range.
It is very basic and missing bunch of checks as aim is the simplicity here.

You can run the script in the following way by which you scan ports between 1 and 1024:

However I need to give some more info in here. If you send a TCP SYN segment to a closed port, normal behavior is to send a TCP RST segment back to the source. Under normal circumstances script runs through the port range and knocks every port on the remote destination. If a TCP RST is received, socket is closed and script knocks the other port in the list but what if you don’t receive any TCP RST back? For example there is a firewall in between and you can’t even knock some ports. Then what happens?  In this case Linux kernel does 5 TCP SYN by default according to my ubuntu sysctl settings;

This is a terrible setting which causes lots of delay in every port knock. That is why to speed up test I decrease this retry value to 1 temporarily

Actually I wanted to set my own retry scheme via python but it seems it isn’t possible to manipulate kernel’s behavior on this.  In python there is a “setsockopt” method of socket by which you can send certain options but no related option I could find in socket manual of Linux. There may be a way but I don’t know it yet.

When you run the test,  you can check the SYN requests with the following tcpdump command, you can have a better picture of what the script is doing;

You have a feedback?

This site uses Akismet to reduce spam. Learn how your comment data is processed.