SoFunction
Updated on 2024-11-16

Python implementation of the port scanner sample code

The socket concept

A socket, also known as a socket, is an endpoint for two-way communication between processes on different hosts. It is simply an agreement between two parties to communicate, and the communication process is accomplished by using the functions in the socket to send or answer network requests.

Sockets originated in Unix, and one of the basic philosophies of Unix/Linux is that "everything is a file", and files are operated in "open", "read/write", and "close" modes. A socket is an implementation of this mode. A socket is a special kind of file, and socket functions perform operations on it, such as reading/writing IO, opening, closing, etc. A socket is a special kind of file, and a socket function performs operations on it.

Basic socket usage

In Python, we use the socket() function to create sockets with the following syntax format:

import socket
(family, type)

function creates a socket socket with two arguments:

  • AF_INET (default) for IPv4, socket.AF_INET6 for IPv6, and socket.AF_UNIX for the UNIX domain protocol family, which can only be used for inter-process communication on a single Unix system.
  • Parameter⼆: type (socket type), such as socket.SOCK_STREAM for TCP (default), SOCK_DGRAM for UDP.

Create tcp socket

import socket 
# Create a socket for tcp
s = (socket.AF_INET, socket.SOCK_STREAM)
# ... Here are the functions for using sockets (omitted)...
# Close the socket
()

Create udp socket

import socket

# Create sockets for udp
s = (socket.AF_INET, socket.SOCK_DGRAM) 
# ... Here are the functions for using sockets (omitted)...
# Close sockets when not in use
()

Socket Built-in Methods

function (math.) descriptive
server-side socket
() Binds an address (host, port) to a socket, which is represented as a tuple (host, port) under AF_INET.
() Starts TCP listening. backlog Specifies the maximum number of connections that the operating system can hang up before rejecting a connection, which is at least one.
() Passively accepts TCP client connections and waits (blocking) for them to arrive.
client socket
() Initializes a TCP server connection, proactively. Normal address is in the form of a tuple (hostname,port) and returns an error if the connection goes wrong.
s.connect_ex() An extended version of the connect() function that returns an error code on error instead of throwing an exception.
Public Use Socket Functions
() Receives TCP data, which is returned as a string. bufsize specifies the maximum amount of data to receive. flag provides additional information about the message, which can usually be ignored.
() Send TCP data, sends the data in string to the connected socket. The return value is the number of bytes to send, which may be smaller than the byte size of the string.
() Send TCP data in its entirety Send TCP data in its entirety. Sends the data in string to the connected socket, but tries to send all the data before returning. Success returns None, failure throws an exception.
() Receiving UDP data is similar to recv(), but the return value is (data,address). where data is the string containing the received data and address is the address of the socket that sent the data.
() Sends UDP data to a socket. address is a tuple of the form (ipaddr, port) specifying the remote address. The return value is the number of bytes sent.
() Close Sockets
() Returns the remote address of the connection socket. The return value is usually a tuple (ipaddr,port).
() Returns the socket's own address. Usually a tuple (ipaddr,port).
(level,optname,value) Sets the value of the given socket option.
(level,optname,buflen) Returns the value of the socket option.
(timeout) Sets the timeout period for socket operations. timeout is a floating point number in seconds. A value of None indicates that there is no timeout. In general, the timeout should be set when the socket is first created, as they may be used for connection operations (such as connect()).
() Returns the value of the current timeout period in seconds, or None if no timeout period is set. ()
(flag) If flag is 0, the socket is set to non-blocking mode, otherwise the socket is set to blocking mode (default). In non-blocking mode, an exception will be thrown if the call to recv() does not find any data, or if the call to send() cannot send data immediately.
() Create a file associated with this socket.

Implementing Port Scanning

After understanding the socket and socket-related functions, we will implement a port scanning tool.

The so-called port scanning, that is, scanning the specified ports of the specified server address, through the scanning results you can know what ports are open on a computer, if you know some knowledge of vulnerabilities or hacking, you can attack through the open ports, and even some of the very powerful hackers, through an inconspicuous port, can cause the entire LAN all the hosts to fall. Of course, the purpose of our study is not to attack.

The principle of port scanning: to the remote end of a specified server port to establish a connection request, if the other party has this service, it will answer, if the other party does not have this service, the other party will not answer. Using this principle, we can specify a number of ports, and then for these interfaces to establish a connection, and get the other party to answer or not, you can know which ports are open.

Above we said socket.connect_ex((ip, port)), call this function to the specified ip and port to issue a connection request, if the return of 0 is proof that the port is open, the return of the error code that the interface is not open.
Here is the code for the port scanning program:

import socket
from datetime import datetime
from  import Pool as ThreadPool


class ScanPort:
    def __init__(self):
         = None

    def scan_port(self, port):
        try:
            s = (socket.AF_INET, socket.SOCK_STREAM)
            res = s.connect_ex((, port))
            if res == 0:  # Port enabled
                print('Ip:{} Port:{} IS OPEN'.format(, port))
            else:
                print('Ip:{} Port:{}: IS NOT OPEN'.format(, port))
        except Exception as e:
            print(e)
        finally:
            ()

    def start(self):
        remote_server = input("Enter the remote host to scan:")
         = (remote_server)
        ports = [i for i in range(1, 1025)]
        (0.5)
        # Start time
        t1 = ()
        # Setting up multiple processes
        threads = []
        pool = ThreadPool(processes=8)
        (self.scan_port, ports)
        ()
        ()

        print('Port scan completed, time taken:', () - t1)


ScanPort().start()

A thread pool has been added to speed things up.

to this article on the implementation of the Python port scanner sample code is introduced to this article, more related Python port scanner content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!