简体   繁体   English

如何为python客户端提供来自python服务器的端口号

[英]How to give a python client a port number from a python server

I'm trying to build a simple python server that a client can connect to without the client having to know the exact portnumber. 我正在尝试构建一个简单的python服务器,客户端可以连接到该服务器,而客户端不必知道确切的端口号。 Is that even possible? 那有可能吗? The thought is to choose a random portnumber and using it for clients to connect. 想法是选择一个随机的端口号,并将其用于客户端连接。

I know you could use bind(host, 0) to get a random port number and socket.getsockname()[1] within the server to get my portnumber. 我知道您可以使用bind(host,0)来获取随机端口号,并在服务器内使用socket.getsockname()[1]来获取我的端口号。 But how could my client get the portnumber? 但是我的客户如何获得端口号?

I have tried socket.getnameinfo() but I don't think I understand how that method really works. 我已经尝试过socket.getnameinfo(),但是我不认为我知道该方法是如何工作的。

In order to do that the server must listen on a certain port(s). 为此,服务器必须在特定端口上进行侦听。 This means the client(s) will need to interact on these ports with it. 这意味着客户端将需要在这些端口上与其交互。

So... no it is impossible to do that on some random unknown port. 所以...不,不可能在某个随机的未知端口上执行此操作。

You need to advertise the port number somehow. 您需要以某种方式公布端口号。 Although DNS doesn't do that (well, you could probably cook up some resource record on the server object, but that's not really done) there are many network services that do. 尽管DNS不能做到这一点(好吧,您可能会在服务器对象上准备一些资源记录,但这确实没有做到),但是有许多网络服务可以做到。 LDAP like active directory (you need write rights), DNS-SD dns service discovery, universal plug and play, service location protocol, all come to mind. 像活动目录(您需要写权限),DNS-SD dns服务发现,通用即插即用,服务位置协议之类的LDAP都浮现在脑海。 You could even record the port number on some web page somewhere and have the client read it. 您甚至可以将端口号记录在某个网页上的某个位置,然后让客户端读取它。

看一下Zeroconf,这似乎是您尝试到达的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM