最近越来越懒,好久没发博文了。
正好最近项目需要,写了两个简单的测试端口连通性的Python脚本,发布出来就当又水了一篇博文。

连通性测试

服务端

import socket
import sys

PORT = int(sys.argv[1])
PROTO = sys.argv[2].lower()

if PROTO == 'tcp':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif PROTO == 'udp':
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
else:
    print("Invalid protocol specified. Use 'tcp' or 'udp'.")
    sys.exit(1)

try:
    sock.bind(('0.0.0.0', PORT))
    print(f"Listening on {PROTO.upper()} port {PORT}...")
except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)

if PROTO == 'tcp':
    sock.listen(5)
    conn, addr = sock.accept()
    with conn:
        print(f"Connected by {addr}")
        response = f"Hello, client! You are connected from {addr[0]}:{addr[1]}."
        conn.sendall(response.encode())
if PROTO == 'udp':
    data, addr = sock.recvfrom(1024)
    print(f"Received from {addr}: {data.decode()}")
    response = f"Hello, client! You are connected from {addr[0]}:{addr[1]}."
    sock.sendto(response.encode(), addr)

客户端

import socket
import sys

SERVER_IP = sys.argv[1]
PORT = int(sys.argv[2])
PROTO = sys.argv[3].lower()

if PROTO == 'tcp':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
elif PROTO == 'udp':
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
else:
    print("Invalid protocol specified. Use 'tcp' or 'udp'.")
    sys.exit(1)

if PROTO == 'udp':
    try:
        message = b"Hello, server!"
        sock.sendto(message, (SERVER_IP, PORT))
        print("Sent message to server.")
        
        data, addr = sock.recvfrom(1024)
        print("Server:", data.decode())
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
else:
    try:
        sock.connect((SERVER_IP, PORT))
        print("Connected to server.")
        
        data = sock.recv(1024)
        print("Server:", data.decode())
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

sock.close()

使用方法也很简单。比如,将服务端和客户端脚本分别保存为server.pyclient.py

服务端执行:

python3 server.py 端口 协议

举例:

python3 server.py 1234 udp

客户端执行:

python3 client.py 服务端IP 端口 协议

举例:

python3 client.py 8.8.8.8 1234 udp
Last modification:April 27, 2024
If you think my article is useful to you, please feel free to appreciate