How to determine if a port is used in C on Linux?

I am writing a simple web server. I want the user to set the port that the server is listening on, but how can I find out if the port that the user enters is used or not? (if I know that it is already in use, I can tell them to enter another one.)

+3
source share
5 answers

Just try bindto port, and if it does not check for EADDRINUSEat errno. This is the only way, since correctly, any such verification should be atomic. If you did a separate check and then tried to bind to the port after you found that it was not in use, another process might bind to the port for a period of time, again causing it to fail. Similarly, if you did a separate check and found that the port was already in use, the process that used it might close the port, exit, or fail over time, again making the wrong result.

(, , ) , , " -?" . , (, , ) .

+8

bind() :

. -1, errno .

EADDRINUSE .

+5

: localhost.

0

bind()

0

Just create a socket and call bind (). If bind () succeeds, go to the listen () function; otherwise, you must follow some error handling procedure, for example, switch to the default port, print an error message and wait for user interaction, or at least log in and log off.

0
source

Source: https://habr.com/ru/post/1776078/


All Articles