wong2
wong2

Reputation: 35700

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

Upvotes: 4

Views: 6075

Answers (5)

khachik
khachik

Reputation: 28703

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

Upvotes: 0

RichardLiu
RichardLiu

Reputation: 1952

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.

Upvotes: 0

user484457
user484457

Reputation: 4811

if bind() shows some error

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318468

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.

Upvotes: 5

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

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.

Upvotes: 10

Related Questions