8

I have to call ping from c++ code.I'd like to easily read the output for further utilizations.

I have come up with two solutions:

  • use a fork and a pipe, redirect ping output to the pipe and then parse it
  • find a library suited for the purpose to use a ping(ip_addresss) function directly

I'd like the latter but i didn't find anything that was clearly a standard solution.

How would you do it ?

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
nios
  • 131
  • 1
  • 1
  • 7

6 Answers6

9
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>


#define PACKETSIZE  64
struct packet
{
    struct icmphdr hdr;
    char msg[PACKETSIZE-sizeof(struct icmphdr)];
};

int pid=-1;
struct protoent *proto=NULL;
int cnt=1;

/*--------------------------------------------------------------------*/
/*--- checksum - standard 1s complement checksum                   ---*/
/*--------------------------------------------------------------------*/
unsigned short checksum(void *b, int len)
{
    unsigned short *buf = b;
    unsigned int sum=0;
    unsigned short result;

    for ( sum = 0; len > 1; len -= 2 )
        sum += *buf++;
    if ( len == 1 )
        sum += *(unsigned char*)buf;
    sum = (sum >> 16) + (sum & 0xFFFF);
    sum += (sum >> 16);
    result = ~sum;
    return result;
}


/*--------------------------------------------------------------------*/
/*--- ping - Create message and send it.                           ---*/
/*    return 0 is ping Ok, return 1 is ping not OK.                ---*/
/*--------------------------------------------------------------------*/
int ping(char *adress)
{
    const int val=255;
    int i, sd;
    struct packet pckt;
    struct sockaddr_in r_addr;
    int loop;
    struct hostent *hname;
    struct sockaddr_in addr_ping,*addr;

    pid = getpid();
    proto = getprotobyname("ICMP");
    hname = gethostbyname(adress);
    bzero(&addr_ping, sizeof(addr_ping));
    addr_ping.sin_family = hname->h_addrtype;
    addr_ping.sin_port = 0;
    addr_ping.sin_addr.s_addr = *(long*)hname->h_addr;

    addr = &addr_ping;

    sd = socket(PF_INET, SOCK_RAW, proto->p_proto);
    if ( sd < 0 )
    {
        perror("socket");
        return 1;
    }
    if ( setsockopt(sd, SOL_IP, IP_TTL, &val, sizeof(val)) != 0)
    {
        perror("Set TTL option");
        return 1;
    }
    if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
    {
        perror("Request nonblocking I/O");
        return 1;
    }

    for (loop=0;loop < 10; loop++)
    {

        int len=sizeof(r_addr);

        if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &len) > 0 )
        {
            return 0;
        }

        bzero(&pckt, sizeof(pckt));
        pckt.hdr.type = ICMP_ECHO;
        pckt.hdr.un.echo.id = pid;
        for ( i = 0; i < sizeof(pckt.msg)-1; i++ )
            pckt.msg[i] = i+'0';
        pckt.msg[i] = 0;
        pckt.hdr.un.echo.sequence = cnt++;
        pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));
        if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)addr, sizeof(*addr)) <= 0 )
            perror("sendto");

        usleep(300000);

    }

    return 1;
}

/*--------------------------------------------------------------------*/
/*--- main - look up host and start ping processes.                ---*/
/*--------------------------------------------------------------------*/
int main(int argc, char *argv[])
{

    if (ping("www.google.com"))
        printf("Ping is not OK. \n");
    else
        printf("Ping is OK. \n");


    return 0;
}
omeraygor
  • 119
  • 1
  • 3
  • This only works for root user as SOCK_RAW needs root level privileges. Read here about socket types: http://www.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.progcomc/socket-types.htm – sb32134 Sep 09 '16 at 13:50
9

From the educational point of view invoking an external binary is very inadvisable. Especially for a simple task such as sending an ICMP echo request, you should learn a bit of socket.

Nicola Bonelli
  • 8,101
  • 4
  • 26
  • 35
4

I would go with your first option. Linux is built around the concept of having small, specialized apps which do one thing really well, communicating with pipes. Your app shouldn't include a library to implement ping, since there is already a built-in command to do it, and it works very well!

e.James
  • 116,942
  • 41
  • 177
  • 214
3

Check out BusyBox's source for 'ping' - you can use the ping4 and ping6 functions. Just be mindful of the GPL.

Spawning 'ping' should work too - check out popen(2) for a simpler API that also runs a shell. If it's a problem, pipe + fork + exec should work.

orip
  • 73,323
  • 21
  • 116
  • 148
  • 1
    Updated source for the ping functions can be found here (since they moved over to Git): http://git.busybox.net/busybox/tree/networking/ping.c – Alex Marshall Oct 30 '13 at 15:56
0

how about https://github.com/octo/liboping ?

    #include <oping.h>

    int main(){
        
        // run ping 100times
        for (uint32_t i=0; i< 100; i++){
            pingobj_t * pingObj = ping_construct();
            ping_host_add(pingObj, "www.gmx.de");

            auto startTime = std::chrono::high_resolution_clock::now();
            auto ret = ping_send(pingObj);
            auto endTime = std::chrono::high_resolution_clock::now();
            if (ret > 0){
                auto duration = (double)std::chrono::duration_cast<std::chrono::microseconds>(endTime - startTime).count()/1000.0;
                std::cout << "success -- ping in " << duration << "ms" << std::endl;
            } else {
                std::cout << "failed" << std::endl;
            }
            ping_destroy(pingObj);
            
            // wait 1sec
            std::this_thread::sleep_for(std::chrono::milliseconds (1000));
        }

    }

liboping should be present in most linux systems

  • install liboping-dev (ex: sudo apt install liboping-dev)
  • linking against liboping
tswaehn
  • 387
  • 1
  • 11
-1

I've managed to do like this:

I use popen which basically creates a pipe, fork and exec Then, if I need, i can wait with pclose.

nios
  • 131
  • 1
  • 1
  • 7