Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

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

like image 951
JohnnyF Avatar asked Jul 28 '14 06:07

JohnnyF


2 Answers

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

like image 95
Rahul R Dhobi Avatar answered Nov 04 '22 07:11

Rahul R Dhobi


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.

like image 29
Jeegar Patel Avatar answered Nov 04 '22 07:11

Jeegar Patel