How to get the local listening ports in real time by C programming?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to get the local listening ports in real time by C programming?



I want to write a LINUX C application that can monitor the system TCP listening ports which provide web service. Whenever a new port is listened, or one port is released, I can detect it in real time.
Does Linux provide system call to provide this feature? Or Should I hook the Kernel function?





Why can’t you use netstat instead?
– danglingpointer
Aug 7 at 10:06





netstat always hangs for a long time when too many tcp connection exist on system. And it's not a system call API.
– river
Aug 8 at 2:16


netstat




1 Answer
1



The code below will help you check if a port is open, if you need real time processing; you may continuously run the program in a separate thread.


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int main(int argc, char *argv)

int portno = 22;
char *hostname = "localhost;

int sockfd;
struct sockaddr_in serv_addr;
struct hostent *server;

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");


server = gethostbyname(hostname);

if (server == NULL)
fprintf(stderr,"ERROR, no such hostn");
exit(0);


bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);

serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
printf("Port is closed");
else
printf("Port is active");


close(sockfd);
return 0;





The legal port ranges from 0 to 65535, if I make a loop to scan all these ports, or create too many threads to do the job, the performance will be a disaster to my server.
– river
Aug 7 at 9:06





The best way is being informed when any port is listened. System hook is the best solution.
– river
Aug 7 at 9:09






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard