#导入模块
import socket
def test_port(host,port):
#创建连接服务对象
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#连接超时3秒
sk.settimeout(3)
try:
#连接服务器ip或域名,端口
#ip/域名为字符串类型str,端口为数字类型int
#connect(),内为元组类型
sk.connect((host, int(port)))
print(host,port,"is ok")
#捕捉异常(即连接失败)
except Exception:
print("\033[1;31;m",host, port, "is close\033[0m")
#关闭连接
sk.close()
if __name__ == '__main__':
#host="www.baidu.com"
port = 80
host = "112.80.248.76"
test_port(host,port)
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>python-sockettitle>
head>
<body>
<p><a href="https://blog.csdn.net/weixin_33736048/article/details/93475477">Python之socket详解a>p>
body>
html>
Python之socket详解可参考https://blog.csdn.net/weixin_33736048/article/details/93475477