Home > front end >  popen for netstat is not working properly in C
popen for netstat is not working properly in C

Time:10-02

I have written a simple code for getting the netstat output in C language . But the output is NULL. When I run the command in linux terminal manually, its working .

#include<stdio.h>
#include<string.h>

int main()
{
        FILE *fp = NULL;
        char HTTPS_LISTEN_STATE[500]={0};
        fp = popen("netstat -an | grep '\b443\b'","r");
        fscanf(fp,"%s", HTTPS_LISTEN_STATE);
        printf("%s\n", HTTPS_LISTEN_STATE);
        fclose(fp);
        return 0;
}

Is there anything needs to be done to get the output?

Output is :

$ ./a.out 

CodePudding user response:

You need to escape the \ inside the string:

fp = popen("netstat -an | grep '\\b443\\b'","r");

Here's the output of the program with that line fixed:

$ cat test.c
#include<stdio.h>
#include<string.h>

int main()
{
        FILE *fp = NULL;
        char HTTPS_LISTEN_STATE[500]={0};
        fp = popen("netstat -an | grep '\\b443\\b'","r");
        fscanf(fp,"%s", HTTPS_LISTEN_STATE);
        printf("%s\n", HTTPS_LISTEN_STATE);
        fclose(fp);
        return 0;
}
$ gcc test.c
$ ./a.out
tcp
  • Related