简体   繁体   中英

How to detect if a port is already in use in C on Linux?

I'm writing a simple web server. I'd like to let the user set the port the server listen to, but how could I know if the port the user input is already in use or not?(if I know it's already in use, I can tell them to input another one.)

Simply try to bind to the port and if it fails check for EADDRINUSE in errno . This is the only way, since to be correct any such check must be atomic. If you did a separate check then tried to bind to the port after finding that it was not in use, another process could bind to the port in the intervening time, again causing it to fail. Similarly, if you did a separate check and found the port already in use, the process that was using it could close the port, exit, or crash in the intervening time, again making the result incorrect.

The point of all this (the reason I wrote a long answer rather than a short answer) is that the correct, robust way to check "Can I do such-and-such?" is almost always to try to do it and check for failure. Any other approach can lead to race conditions, and in many cases race conditions (although probably not yours) race conditions are security vulnerabilities.

bind() will fail:

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

EADDRINUSE The given address is already in use.

另一种方法:尝试连接到localhost上的该端口。

如果bind()显示一些错误

Just create a socket and call bind(). If bind() success, then proceed to listen(), otherwise you should perform some error handling procedure, such as switch to a default port, print error message and wait for user interact, or at least log and quit.

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