nopeman
nopeman

Reputation: 13

Reading console output for ping in C

I am currently trying to write some tests with pinging different IPs. I got the system() for those commands, but I would like to read console output and based on that write string(like TEST PASSED/TEST FAILED). Is there a way to do it without saving the console log to file and reading from it (seems too convoluted to me).

Below is the simple code example I made:

switch (choice) {
    case 1:
        system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(DEI));
        printf("----------------------------------------------------\n\n");
        break;

    case 2:
        system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(AURIX));
        printf("----------------------------------------------------\n\n");
        break;

    case 3:
        system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(MID2EI));
        printf("----------------------------------------------------\n\n");
        break;

    case 4:
        system("ping -c " STR(COUNTER)" -w "STR(TIMER) " " STR(VEI));
        printf("----------------------------------------------------\n\n");
        break;

    case 5:
        printf("Quitting...\n");
        sleep(1000);
        running = false;
        break;

    default:
        printf("Wrong input. Try again.\n");
        printf("----------------------------------------------------\n\n");
        break;
}

Upvotes: 1

Views: 1113

Answers (1)

lnksz
lnksz

Reputation: 501

If you are interested in a crude availability monitor, checking ping's exit value could be done via the macros from <sys/wait.h>

#include <sys/wait.h>
int exit_status = system("ping -c 1 8.8.8.8");

if (WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == 0)
    puts("Reachable!");
else
    puts("Unreachable");

If you really want to parse the output, the popen() example from https://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html is quite to the point:

#include <stdio.h>
...


FILE *fp;
int status;
char path[PATH_MAX];


fp = popen("ls *", "r");
if (fp == NULL)
    /* Handle error */;


while (fgets(path, PATH_MAX, fp) != NULL)
    printf("%s", path);


status = pclose(fp);
if (status == -1) {
    /* Error reported by pclose() */
    ...
} else {
    /* Use macros described under wait() to inspect `status' in order
       to determine success/failure of command executed by popen() */
    ...
}

Upvotes: 1

Related Questions