利用python自带的socket,检测端口是否被占用
import socket
def check_port(host,port):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((host,port))
# 关闭端口,2的意思是:将来禁止读和写
s.shutdown(2)
except OSError as msg:
print('port%s is available!'% port)
print(msg)
return True
else:
print('port %s alreadt be inuse!'%port)
return False
if __name__ == '__main__':
host='127.0.0.1'
port=4237
check_port(host,port)