Home > front end >  how to get ip address as a string
how to get ip address as a string

Time:07-25

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.

CodePudding user response:

ip is not initialized.

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

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

CodePudding user response:

You can write to the ip array directly:

for(unsigned int n = 0; n < i->p_int;   n)
{
    ip  = sprintf(ip, "%d.", i->p_data[i]);
}
*--ip = 0; // remove the trailing dot

Note that any function out of the printf returns the number of bytes it has written.

Of course you'd backup original value of ip to be able to return it...

Apart from you need to check the return value of malloc as 0___________ mentioned already in his answer.

Note, too, that the separator character in IPv6 case typically rather is a colon (:) than a period (.), so you might consider that for n > 4.

If you are guaranteed to have IPv4 only you could do instead:

if(i->p_int == 4) // otherwise you consider i invalid anyway...
{
    printf("%d.%d.%d.%d", i->p_data[0], i->p_data[1], i->p_data[2], i->p_data[3]);
}
  • Related