cstringlibpcap

how to get ip address as a string


I'm developing a network sniffer based on libpcap in C programming language.

Already I have one function which can print the IP address as follows:

void print_ipaddress(ipaddress *i) {
    for (unsigned int n = 0; n < i->p_int; n++) {
        printf("%d", i->p_data[n]);
        if (n < i->p_int - 1) printf(".");
    }
    printf("\n"); 
}


the ipaddress structure is created by my program and the data is copied from libpcap. (In fact, you don't need to care about the details about this function). The above function can print the ip address correctly.

Next step, I want to store the ip address as a string. So I write the following function:

char* get_ipaddress(ipaddress *i) {
    char *ip = malloc(sizeof(char)*20);
    for(unsigned int n = 0; n < i->p_int; n++) {
        char s[3];
        sprintf(s, "%d", i->p_data[n]);
        strcat(ip, s);
        if (n < i->p_int - 1) {
            strcat(ip, ".");
        }
    }
    return ip;
}

But the string contains some mess code as follows:

I'V172.17.98.31

I was a little bit confused how to handle each byte as a string and append them together.


Solution

  • ip is not initialized.

    char *ip = malloc(20);
    ip[0] = 0;
    

    You should check the result of malloc to avoid dereferencing the NULL pointer