开发者

Converting a 4 byte ip address to standard dotted decimal notation

开发者 https://www.devze.com 2023-01-23 05:35 出处:网络
If I have a 4 byte address stored in 开发者_运维知识库char address[4] and the contents are: address[0] = \'\\x80\';

If I have a 4 byte address stored in 开发者_运维知识库char address[4] and the contents are:

address[0] = '\x80';
address[1] = '\xAB';
address[2] = '\x0A';
address[3] = '\x1C';

// all together: 80 AB 0A 1C

I want to convert it to a character array that looks like "128.171.10.28", since 80 in hex is 128, AB in hex is 171 and so on.

How can I do this?


char saddr[16];
sprintf(saddr, "%d.%d.%d.%d", (unsigned char)address[0], (unsigned char)address[1], (unsigned char)address[2], (unsigned char)address[3]);

or

char saddr[16];
unsigned char *addr = (unsigned char*)address;

sprintf(saddr, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);

or, as pointed out by dreamlax:

char saddr[16];
sprintf(saddr, "%hhu.%hhu.%hhu.%hhu", address[0], address[1], address[2], address[3]);


An IP address ist just the individual octets printed as decimal separated by a .

  printf("%d.%d.%d.%d",address[0],address[1],address[2],address[3]);

You probably should make your char address[4] an unsigned char address[4]


Using %u would be even better.

0

精彩评论

暂无评论...
验证码 换一张
取 消