This article is participating in Python Theme Month. See the link for details.

On the server, there are many times when you need to observe the usage of ports. Of course, we can use the mature tool Nmap to do this, but can we use Python socket natively to do this?

1. Socket concept

Socket socket is widely used in Internet communication. Applications usually send requests or answer network requests through the socket to complete the communication between hosts or processes on a computer.

The socket module in Python provides access to the BSD socket interface. It includes socket classes for handling the actual data channels, as well as functions for network-related tasks, such as converting server names to addresses and formatting data to be sent over the network.

The following diagram illustrates the process of using sockets to communicate.

Basic socket usage

Let’s get familiar with the basic usage of socket functions. In Python, after importing the socket, use the socket.socket() method to create a socket in the following syntax:

socket = socket.socket([family[, type[, proto]]])
Copy the code

Parameter Description:

  • family: Socket family that can be enabledAF_UNIXorAF_INET.
  • type: Socket type, depending on whether it is connection-oriented or non-connection-orientedSOCK_STREAMorSOCK_DGRAM, the difference between TCP and UDP.
  • Protocol: The default value is 0.

If socket.socket() is used directly, the default values are used.

Create a TCP socket (streaming)

socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
Copy the code

Create a UDP socket (datagram)

socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
Copy the code

Translate a host name into IPv4 address format

gethostbyname("host") 
Copy the code

Translate a host name into IPv4 address format, extending the interface

socket.gethostbyname_ex("host")  
Copy the code

Get a fully qualified domain name

Socket. Getfqdn (" 8.8.8.8 ")Copy the code

Gets the hostname of the machine

socket.gethostname()  
Copy the code

Exception handling

Exception handling
Copy the code

Three, scanning port combat

#! /usr/bin/env python import socket import subprocess import sys import platform from datetime import datetime # If platform.system() == "Windows": subprocess.call(' CLS ', shell=True) else: Host remoteServer = input("Enter a remote host to scan: ") remoteServerIP = socket.gethostByName (remoteServer) # Print format below # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- # both Please wait, Scanning remote host 110.242.68.3 # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- print (" - "* 60) print ("Please wait, scanning remote host", RemoteServerIP) print ("-" * 60) print ("-" * 60) Try: for port in range(1,1025): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((remoteServerIP, port)) if result == 0: print ("Port {}: Open".format(port)) sock.close() except KeyboardInterrupt: print ("You pressed Ctrl+C") sys.exit() except socket.gaierror: print ('Hostname could not be resolved. Exiting') sys.exit() except socket.error: Print ("Couldn't connect to server") sys.exit() # return time t2 T2 = datetime.now() # return time total = T2-T1 # return time to console print ('Scanning Completed in: ', total)Copy the code