简体   繁体   中英

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?

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 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM