Now that we understand sockets, let's build a simple port-scanner. The idea of a port scanner is to run through a list of ports, testing to see if they are open. We can do this because the steps for using sockets for sending data is first you make the connection, then you try to off-load the request. Re-visiting our ship metaphor, the dock has no idea what contents are in the ship. Thus, if the port is open, the ship can at least dock before anyone knows whether or not what the ship is carrying is supposed to be there.
With our port scanner, we just attempt to dock at various ports, and do nothing else. If we're permitted to dock / connect to open ports, then we know at least the port is open. This is a form of "reconnaissance" for hackers and penetration testers.
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) target = input('What website to scan?: ')
Here is code you should recognize up to this point. For the target, you could enter website that allows you to do this. Check out "https://www.hackthissite.org/", or you can always target your own servers.
It should be noted that port scanning can be seen as, or construed as, a crime. You should never execute a port scanner against any website or IP address without explicit, written, permission from the owner of the server or computer that you are targeting. Port scanning is akin to going to someones house and checking out all of their doors and windows. There is really only reason why anyone would do this, and it is to assess securities and vulnerabilities. Thus, if you have no good reason to be testing these things, it can be assumed you are a criminal.
Also, I have been locked out of my own servers before for running various penetration tests, which was part of the test. A lot of servers have security software that identifies and protects against things like port scans, slowing them down or just outright denying any further connections from the source IP address. Thus, you might find yourself unable to access a server after running a test. For this reason, you may want to use "https://www.hackthissite.org/" instead of just any random site, or even your own.
def pscan(port): try: con = s.connect((target,port)) return True except: return False for x in range(25): if pscan(x): print('Port',x,'is open')
That's all, for a simple port scanner. What we've done above is simply attempt a connection to a port. If that is successful, our function returns a True, otherwise a False. If True is returned, then our little program will print out the successful port to the console.