开发者

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.


if bind() shows some error


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.


Another approach: Try to connect to that port on localhost.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜