简体   繁体   中英

How to choose port in socket programming?

I'm currently learning socket programming in python, and I'm puzzled on how to select the ports for my servers to listen to. I'm aware that I can't choose some specific range (up to 3000 or something?), so I selected the ports way beyond that number (7777 to be precise).

In my scenario, I would like to test my program using different number of servers (multiples of 12 up to 96). So far I'm testing my program with 12 server codes, assigning the host to localhost , and port numbers from 7777 to 7788 .

Sometimes when I run my program, python intepreter says:

Traceback (most recent call last):
  File "/home/myUserName/sockettutorial/sockettest4/ppc1/dir12/nwserver12.py", line 9, in <module>
    s.bind((host,port))
  File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

despite I've killed all the relevant processes that may still listen to the said ports (using netstat -plan to check for the PIDs of those processes).

I have included this part in my server codes:

s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

My problem here is that despite the error, the program works as expected, and sometimes when I run my program, I didn't get this error at all and sometimes I did. However, the error itself is kinda annoying and if I want to get rid of it, is there any way to let the machine/host assign the available ports for the servers, or do I have to manually assign them?

Thank you for all the answers!

When you bind a server to a port to listen for incoming connections, you need to specify the port. A lot of services have a "standard" port which they run on by default, eg HTTP: 80, HTTPS: 443, SSH: 22. This is so clients know which port to send data to when they connect (if something is on a random port, the client can't connect).

If you want to have the OS pick a port for you when you bind, you can bind to port zero. You can then find out what port you were assigned by using getsockname . Example:

>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> s.bind(('127.0.0.1', 0))
>>> s.getsockname()
('127.0.0.1', 42171)

Port numbers are a short int (16 bits), so their range is 0-65535. Ports below 1000 are usually reserved for "known" services, like those mentioned above, and services serving on them usually need to be run as root.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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