Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

sockets

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

like image 937
wong2 Avatar asked Dec 09 '22 12:12

wong2


2 Answers

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.

like image 171
R.. GitHub STOP HELPING ICE Avatar answered Dec 12 '22 00:12

R.. GitHub STOP HELPING ICE


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.

like image 38
ThiefMaster Avatar answered Dec 12 '22 01:12

ThiefMaster