简体   繁体   English

Python套接字端口使用

[英]Python Socket Port Use

I'm trying to set a server application and client application in which the server will listen for connections using localhost and a certain port - however - if for example, the port is 2001 - if that port is not available, I would like to use 2002, if that's not available then 2003 - etc. How do I implement that in my code? 我正在尝试设置服务器应用程序和客户端应用程序,其中服务器将使用localhost和某个端口来侦听连接-但是-例如,如果端口是2001-如果该端口不可用,我想使用2002,如果不可用,则使用2003-等等。如何在代码中实现呢?

example = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
example.bind(("localhost",2001))

may be just loop around till it doesnt generate an exception 可能只是循环直到它不产生异常

port = 2001
while True:
    try:
        example.bind(("localhost",port))
    except:
        port += 1
        continue
    break

Rather than try to find an available free port in some kind of loop you can bind to port 0 ( zero ) and let your OS bind to a suitable free port. 您可以绑定到端口0 ),然后让您的操作系统绑定到合适的空闲端口,而不是尝试在某种循环中找到可用的空闲端口。 You can then access the bound port via introspecting the server socket object using socket.getsockname() 然后,您可以使用socket.getsockname()通过内省服务器套接字对象来访问绑定端口。

I prefer to bind the socket to a random port number assigned by the kernel and then query for the port number opened. 我更喜欢将套接字绑定到内核分配的随机端口号,然后查询打开的端口号。

example.bind((host,0)) #0-random, free port number
example.getsockname()

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

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