title: Python端口占用测试(检测Socket)
tags:
- python
- Socket
categories: - [学习笔记, python]
description: 一个简单的端口占用测试
目录
客户端
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py
from ast import Try
import socket # 导入 socket 模块
import sys
socketList = []
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口号
for i in range(1,1100):
s = socket.socket() # 创建 socket 对象
localHostAndPort = (host,i)
try:
s.bind(localHostAndPort)
if s.connect((host, port)) == socket.error:
print('FAILED', i)
print(s.recv(1024).decode(), i)
socketList.append(s)
except OSError as e:
print(localHostAndPort, "OSError:", e, sys.exc_info)
input = input()
if input == 'exit':
for skt in socketList:
skt.close()
服务端
#!/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() # 关闭连接