JohnnyF
JohnnyF

Reputation: 1101

how to check if a port is free in linux using c

i have never written anything like it, how do i check things like if a port is empty using c program in Linux environment thanks a lot.

ps looking for a way, by not using bind or connect and checking if it failed.

edit i cant use bind or connect, looking for faster way to find 3k ports that are free in a row

Upvotes: 6

Views: 5254

Answers (4)

JohnnyF
JohnnyF

Reputation: 1101

i had same problem the question is do you need to check just one port or many ports

If you need to check just one or few use bind, if it works then its free (and dont forget to free the socket)

if like me you need to check many ports, then what worked for me is run system('netstat -tulpn') and redirect output to a file/variable and then on this info search for ":{yourport}"

worked for me

ps if like me you need to keep them free, tell your computer not to randomlly allocate ports in that area

Upvotes: -1

Vinay Shukla
Vinay Shukla

Reputation: 1844

How about you using bind() directly, and if it doesn't succeed you can try another port.

You just checked, that a port was free, but someone already used it would be a race condition,so checking if a port is free and then binding it is not possible

You can also read /proc/net/tcp for help but the race condition can still occur.

Upvotes: 0

Jeegar Patel
Jeegar Patel

Reputation: 27210

Run following command using system() or popen()

netstat -antu

It will give list of all used port of your machine. You need to parse output of that command and then you will have list of all busy port.

Upvotes: 1

Rahul R Dhobi
Rahul R Dhobi

Reputation: 5806

Better way is to use next free port,You can also use 0 port bind will use the next available port.

You can get port selected by bind() by following code

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) != -1)
  printf("port number %d\n", ntohs(sin.sin_port)); 

Also refer How to bind to any available port? for more inforamtion

Upvotes: 2

Related Questions