MBU
MBU

Reputation: 5098

Converting a 4 byte ip address to standard dotted decimal notation

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?

Upvotes: 3

Views: 8554

Answers (3)

sje397
sje397

Reputation: 41862

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]);

Upvotes: 9

0xDEADBEEF
0xDEADBEEF

Reputation: 868

Using %u would be even better.

Upvotes: -1

nos
nos

Reputation: 229344

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]

Upvotes: 5

Related Questions