本文介绍了在本地主机上,我如何选择一个可用的端口号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用进程间通信,因为我不知道如何在 Windows 下使用命名管道,所以我想我会使用网络套接字.一切都发生在本地.服务器能够在单独的进程中启动从服务器并侦听某个端口.奴隶做他们的工作并将结果提交给主人.我如何确定哪个端口可用?我假设我无法侦听端口 80 或 21?

I'm trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21?

我正在使用 Python,如果这样可以减少选择.

I'm using Python, if that cuts the choices down.

推荐答案

不要绑定到特定端口.相反,绑定到端口 0:

Do not bind to a specific port. Instead, bind to port 0:

sock.bind(('', 0))

然后操作系统会为您选择一个可用的端口.您可以使用 sock.getsockname()[1] 获取选择的端口,并将其传递给从属设备,以便它们可以重新连接.

The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1], and pass it on to the slaves so that they can connect back.

sock 是您创建的套接字,由 socket.socket 返回.

sock is the socket that you created, returned by socket.socket.

这篇关于在本地主机上,我如何选择一个可用的端口号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:22