O'Reilly logo

Mastering Python for Networking and Security by Jose Manuel Ortega

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Port scanner with sockets

Sockets are the fundamental building block for network communications and in an easy way we can check whether a specific port is open, closed, or filtered by calling the connect_ex method.

For example, we could have a function that accepts by parameters an IP and a list of ports and return for each port whether it is open or closed.

In this example, we need to import the socket and sys modules. If we execute the function from our main program, we see how it checks each of the ports and returns whether it is open or closed for a specific IP address. The first parameter can be either an IP address or a domain name since the module is able to resolve a name from an IP and vice versa.

You can find the following code ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required