G
N
I
D
A
O
L

Python端口占用代码

windows 端口相关

动态端口查询

netsh int ipv4 show dynamicport tcp

协议 tcp 动态端口范围
---------------------------------
启动端口        : 49152
端口数          : 16384

动态端口设置

需要再管理员命令行下:

netsh int ipv4 set dynamicport tcp start=49152 num=2000

Python实现的端口测试接口

客户端

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py
 
from ast import Try
import socket               # 导入 socket 模块
import sys

socketList = []

host = socket.gethostname() # 获取本地主机名
remoteHost = '192.168.3.171'
remotePort = 6000                # 设置端口号

errNum = 0
ToTalNum = 0
errPorts = {}

print("请通过\'netsh int ipv4 show dynamicport tcp\'查看启动端口和端口数,一般情况下该值为49152")
start = eval(input("启动端口:"))
end = eval(input("终止端口:"))

for i in range(start , end): 
    ToTalNum += 1
    s = socket.socket()         # 创建 socket 对象
    localHostAndPort = (host,i)
    try:
        s.bind(localHostAndPort)
        if s.connect((remoteHost, remotePort)) == socket.error:
            print('FAILED', i)
        print(s.recv(1024).decode(), i)
        socketList.append(s)
    except OSError as e:
        errNum += 1
        errPorts[i] = (localHostAndPort, "OSError:", e)

print("Total Port Number(%r)"%ToTalNum, "Error Port Number(%r)"%errNum)
print("Error Ports:")
for err in errPorts.keys():
    print(err, errPorts[err])

if len(errPorts) == 0:
    print("All Ports success (%d) ~"%start, "(%d)"% end)

print("输入\'exit\'关闭CLIENT:")
char = input()
while char != "exit":
	# print(char)
	char = input()

for skt in socketList:
    skt.close()
# print(socketList)

服务端

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py
 
import socket               # 导入 socket 模块
 
s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口
s.bind((host, port))        # 绑定端口

msg = 'Success!'  #strip默认取出字符串的头尾空格
 
s.listen(5)                 # 等待客户端连接
while True:
    c,addr = s.accept()     # 建立客户端连接
    print('连接地址:', addr)
    c.send(msg.encode('utf-8'))
    c.close()                # 关闭连接
posted @ 2022-01-21 00:38  StimuMing  阅读(192)  评论(0编辑  收藏  举报