在localhost上,如何选择一个空闲端口号? [英] On localhost, how do I pick a free port number?

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

问题描述

我正在尝试进行进程间通信,并且由于无法弄清楚如何在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,例如sock.bind(('', 0)).然后,操作系统将为您选择一个可用端口.您可以使用sock.getsockname()[1]获取选择的端口,并将其传递给从站,以便它们可以重新连接.

Do not bind to a specific port, or bind to port 0, e.g. sock.bind(('', 0)). 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆