如何用Python扫描IP端口并打印响应状态码?代码异常求推荐方案
如何检测指定IP端口的HTTP状态码?
嘿,我来帮你搞定这个问题!你想要检测指定IP端口的HTTP状态码,但用了无效端口811450代码却没报错,这是因为你的现有代码存在几个关键问题,而且手动用socket处理HTTP实在太折腾了。我给你梳理下问题,再推荐更靠谱的实现方法:
先说说你现有代码的问题
- 端口
port被定义成了字符串,而socket.connect需要整数类型的端口,这会直接导致连接失败,但你的代码没做异常捕获,所以没报错就悄悄跳过了 mysocket类的connect、mysend、myreceive方法缩进错误,它们应该属于类的方法,现在的写法会直接触发语法错误- 代码里用到的
MSGLEN变量根本没定义,调用mysend或myreceive的时候会直接抛出NameError - 手动用socket构建HTTP请求太底层了,你需要自己处理请求头、响应解析,还要处理各种网络异常,这既麻烦又容易出错,完全没必要
推荐的实现方法
方法一:用requests库(最简单高效)
requests是Python里处理HTTP请求的首选库,它封装了所有细节,异常处理也很完善。如果你的环境还没装,先运行pip install requests安装。
示例代码:
import requests def get_http_status(ip, port): url = f"http://{ip}:{port}" try: response = requests.get(url, timeout=5) return f"{response.status_code} {response.reason}" except requests.exceptions.ConnectionError: return "连接失败:端口未开放或无服务运行" except requests.exceptions.Timeout: return "请求超时" except Exception as e: return f"发生错误:{str(e)}" # 测试 print(get_http_status("xx.xx.xx.xxx", 80)) # 应该返回200 OK print(get_http_status("xx.xx.xx.xxx", 811450)) # 返回连接失败提示
方法二:用Python标准库http.client(无需额外安装)
如果你不想用第三方库,用标准库的http.client(Python2里是httplib)也能实现,不需要额外安装依赖:
import http.client import socket def get_http_status(ip, port): try: conn = http.client.HTTPConnection(ip, port, timeout=5) conn.request("GET", "/") response = conn.getresponse() status = f"{response.status} {response.reason}" conn.close() return status except (socket.timeout, ConnectionRefusedError): return "连接失败:端口未开放或无服务运行" except Exception as e: return f"发生错误:{str(e)}" # 测试 print(get_http_status("xx.xx.xx.xxx", 80)) print(get_http_status("xx.xx.xx.xxx", 811450))
如果你一定要用socket手动实现(不推荐)
如果坚持要用socket自己处理,那得修正你的代码,加上异常处理和必要的定义,才能正常工作:
import socket class mysocket: def __init__(self, sock=None): if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock self.MSGLEN = 1024 # 定义接收的最大字节数 def connect(self, host, port): try: self.sock.connect((host, port)) except (socket.error, ConnectionRefusedError) as e: raise RuntimeError(f"连接失败:{str(e)}") def mysend(self, msg): totalsent = 0 msg_bytes = msg.encode('utf-8') MSGLEN = len(msg_bytes) while totalsent < MSGLEN: sent = self.sock.send(msg_bytes[totalsent:]) if sent == 0: raise RuntimeError("socket connection broken") totalsent += sent def myreceive(self): chunks = [] bytes_recd = 0 while bytes_recd < self.MSGLEN: chunk = self.sock.recv(min(self.MSGLEN - bytes_recd, 2048)) if chunk == b'': raise RuntimeError("socket connection broken") chunks.append(chunk) bytes_recd += len(chunk) return b''.join(chunks).decode('utf-8') # 使用示例 host = "xx.xx.xx.xxx" port = 811450 # 注意改成整数类型 try: s = mysocket() s.connect(host, port) # 发送标准HTTP GET请求 s.mysend("GET / HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n".format(host)) response = s.myreceive() # 解析响应中的状态行 status_line = response.split('\r\n')[0] print(status_line.split(' ', 2)[1], status_line.split(' ', 2)[2]) except Exception as e: print(e)
内容的提问来源于stack exchange,提问作者Codieroot
相关产品推荐
相关产品推荐

