This is the 12th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge

The socket concept

Socket is also known as the socket, can be seen as the process between different hosts two-way communication endpoint, simply said that the two sides of the communication is a kind of convention, with socket related functions to complete the communication process, send network request or reply network request.

Socket originated in Unix, and one of the basic Unix/Linux philosophies is that “everything is a file.” Files are operated in “open”, “read and write”, and “close” modes. Socket is an implementation of this pattern. In plain English, socket is a special file. Some socket functions operate on it, including reading/writing IO, opening, closing, etc.

Basic Socket Usage

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

import socket
socket.socket(family, type)
Copy the code

The socket.socket function creates a socket. This function takes two arguments:

  • Parameter 1: family(address cluster)socket.AF_INET(Default) IPv4,socket.AF_INET6, for IPv6, andsocket.AF_UNIXIs a UNIX domain protocol family and can only be used for interprocess communication in a single UNIX system.
  • Parameter 2: type (socket type). For example, socket.SOCK_STREAM is TCP(default) and SOCK_DGRAM is UDP.

The TCP socket is created

import socket 


# Create TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#... Here's how to use sockets (omitted)...
Close the socket
s.close()
Copy the code

Create a UDP socket

import socket 

# Create udp socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
#... Here's how to use sockets (omitted)...
# Close the socket when not in use
s.close()
Copy the code

The socket is built in

function describe
Server socket
s.bind() Bind an address (host, port) to a socket, in the form of a tuple (host, port) under AF_INET.
s.listen() Start TCP listening. Backlog specifies the maximum number of connections that the operating system can suspend before a connection is denied. The value must be at least 1.
s.accept() Passively accept TCP client connections and wait (blocking) for a connection to arrive.
Client socket
s.connect() Initializes the TCP server connection. Generally, the address format is a tuple (hostname,port). If the connection fails, socket. Error is returned.
s.connect_ex() An extended version of the connect() function that returns an error code instead of throwing an exception.
A socket function for public use
s.recv() TCP data is received. The data is returned as a string. Bufsize specifies the maximum amount of data to receive. The flag provides additional information about the message and can usually be ignored.
s.send() Send TCP data, sending the data in the string to the connected socket. The return value is the number of bytes to send, which may be less than the size of the string in bytes.
s.sendall() TCP data is sent in full. Sends the data in the string to the connected socket, but attempts to send all the data before returning. Returns None on success, and raises an exception on failure.
s.recvfrom() Receives UDP data, similar to recv(), but returns the value (data,address). Where data is the string containing the received data and address is the address of the socket from which the data was sent.
s.sendto() 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.
s.close() Close the socket
s.getpeername() Returns the remote address to which the socket is connected. The return value is usually a tuple (ipaddr,port).
s.getsockname() Returns the address of the socket itself. This is usually a tuple (ipaddr,port).
s.setsockopt(level,optname,value) Sets the value of the given socket option.
s.getsockopt(level,optname,buflen) Returns the value of the socket option.
s.settimeout(timeout) Sets the timeout period for a socket operation. Timeout is a floating-point number in seconds. A value of None indicates that there is no timeout. In general, timeout periods should be set when the socket is first created, as they may be used for connection operations such as connect()
s.gettimeout() Returns the value of the current timeout period, in seconds, or None if no timeout period is set. s.fileno()
s.setblocking(flag) If flag is 0, set the socket to non-blocking mode. Otherwise, set the socket to blocking mode (default). In non-blocking mode, a socket.error exception is raised if the recv() call finds no data, or if the send() call fails to send data immediately.
s.makefile() Creates a file associated with the socket.

Implement port scanning

After understanding socket and socket related functions, we will implement a port scanning gadget. The so-called port scanning, is to specify the server address specified port scan, scan results can know what ports are open on a computer, if you know some knowledge of holes or hacker attacks, can attack through the open ports, and even some fierce of hackers, through a small port, It can destroy every host on the entire LAN. Of course, the purpose of learning is not to attack.

The principle of port scanning is as follows: The remote server sends a connection request to a specified port. If the remote server provides the service, the remote server responds. If the remote server does not provide the service, the remote server does not respond. Using this principle, we can specify a number of ports, and then establish a connection to each of these interfaces, and get the other party whether to reply, we can know which ports are open.

Socket.connect_ex ((IP, port)) is called to make a connection request for the specified IP and port. If 0 is returned, the port is open. If 0 is returned, the interface is not open. Here is the code for the port scanner:

import socket
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool


class ScanPort:
    def __init__(self) :
        self.ip = None

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

    def start(self) :
        remote_server = input("Enter the remote host you want to scan :")
        self.ip = socket.gethostbyname(remote_server)
        ports = [i for i in range(1.1025)]
        socket.setdefaulttimeout(0.5)
        # Start time
        t1 = datetime.now()
        # Set multiple processes
        threads = []
        pool = ThreadPool(processes=8)
        pool.map(self.scan_port, ports)
        pool.close()
        pool.join()

        print('Port scanning completed, time consuming:', datetime.now() - t1)


ScanPort().start()
Copy the code

Added thread pool to speed up operation. Run the screenshot:

Finally, I would like to thank my girlfriend for her tolerance, understanding and support in work and life.