Search code examples
ciphexdecimalstrtol

Convert IP address from hex to dec using strtol()


I put an IP address from frame to struct:

unsigned char destination_address[4];

In my main program I load a struct:

struct ipv4 naglowek_ipv4;
upakuj_ipv4(bufor_eth_ipv4, &naglowek_ipv4);

And try show this in a "human-readable format":

printf("Destination Adress: %ld.%ld.%ld.%ld\n",
    strtol(naglowek_ipv4.destination_address[0],NULL,16),
    strtol(naglowek_ipv4.destination_address[1],NULL,16),
    strtol(naglowek_ipv4.destination_address[2],NULL,16),
    strtol(naglowek_ipv4.destination_address[3]));

This doesn't display the way I think it should. Does anyone have any idea why?


Solution

  • The destination_address is not a string, it's just array of four bytes. So simplify your call to:

    printf("Destination Adress: %d.%d.%d.%d\n",
            naglowek_ipv4.destination_address[0],
            naglowek_ipv4.destination_address[1],
            naglowek_ipv4.destination_address[2],
            naglowek_ipv4.destination_address[3]);
    

    You would notice if you included the declaration of strtol (and also the fact you don't pass enough parameters to the last invocation):

    #include <stdlib.h> /* provides strtol() function */