检查端口是否忙于考虑端口转发

时间:2018-08-19 01:06:23

标签: python

我有一个python脚本,尝试使用某个任意端口运行http服务器,如果端口繁忙则失败,它将在下一个端口上再次尝试,直到一个正常工作为止。

from http.server import SimpleHTTPRequestHandler, HTTPServer

host = "0.0.0.0"
port = 8023
success_running = False
while not success_running:
    try:
        httpd = HTTPServer((host, port), SimpleHTTPRequestHandler)
        success_running = True
    except OSError as e:
        if e.errno == 48 or e.errno == 98:
            new_port = port + 1
            print("port {} already in use, trying {}".format(port, new_port))
            port = new_port
        else:
            print("error running http server {}".format(e))

print("running using port {}".format(port))

while True:
    httpd.handle_request()

这通常可以正常工作,但是有时我通过ssh连接到某些服务器进行端口转发。例如,我可能正在转发端口8023,这是我的脚本尝试执行的第一件事,但未将其检测为繁忙端口。结果,它成功使用端口8023运行服务器,但是当我尝试访问http://localhost:8023时,它显示的是来自服务器的转发结果。如何使我的脚本检测到8023实际上是一个“繁忙”端口,然后尝试另一个端口?

0 个答案:

没有答案
相关问题