在创建 tcp server 的时候,首先检测端口是否被占用。
代码如下:
----------------------------------------
import socket
def net_is_used(port, ip='192.168.1.111'):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((ip,port))
s.shutdown(2)
print('sorry, %s:%d is used' % (ip,port))
return True
except Exception as e:
print('hahahaha %s:%d is unused' % (ip,port))
print(e)
return False
------------------------------------------
调用一下
net_is_used(7777)
------------------------------------------
打印信息:"sorry, 192.168.1.111:7777 is used " 说明已经被占用
(完)