1

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?

example = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
example.bind(("localhost",2001))
1
  • 2
    you can use example.bind(address, port) inside a try -except.... Commented Dec 11, 2013 at 12:26

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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. You can then access the bound port via introspecting the server socket object using socket.getsockname()

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.