检查端口是否在 Python3 中打开?

Check If Port is Open in Python3?

In python 3 给定一个 IP 地址,我想检查特定端口是否为 TCP 连接打开。我该怎么做?

请注意,我根本不想等待。如果没有立即收到回复,则只需报告它已关闭。

这是我从 https://www.kite.com/python/answers/how-to-check-if-a-network-port-is-open-in-python

获得的 Python3 示例
import socket

a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

port = 8080
location = ("127.0.0.1", port)
check = a_socket.connect_ex(location)

if check == 0:
   print("Port is open")
else:
   print("Port is not open")

您可以这样做来检查端口是否被占用或是否打开:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

location = ("127.0.0.1", 80)
result = sock.connect_ex(location)

if result == 0:
   print("Port is open")
else:
   print("Port is closed")

其中,socket.AF_INET指定IP地址族(IPv4),socket.SOCK_STREAM指定套接字类型(TCP)。

您可以使用简单的脚本

#!/usr/bin/python

import socket

host = "127.0.0.1"
port = 9003

# try to connect to a bind shell
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    print(f"Port {port} is open")
    s.close()
except socket.error:
    print(f"Port {port} closed.")

常量 socket.SOCK_STREAM 此处响应 TCP 连接。