How to check if a port is free on Linux using c

I never wrote anything like this, how can I check things like if the port is empty using the c program in Linux Thank you very much.

ps searches for a way without using bind or connect and checking if it failed.

change i can't use bind or connect looking for a faster way to find 3k ports free in string

+4
source share
4 answers

I had the same problem the question is that you only need to check one port or many ports

If you need to check only one or several usage links, if it works, then its free (and don't forget to free the socket)

, system ('netstat -tulpn') / ": {yourport}"

, , ,

-1

, 0- bind .

, bind(),

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

. ?

+2

, system() popen()

netstat -antu

. , .

0

, bind(), , .

, , - , , , , .

/proc/net/tcp , .

0

All Articles