i have a hex value say for example 0x0a010203 and i want to convert it to a string such that after conversion it should be like "10.1.2.3",How to extract the individual fields from the hex value ?
Fill a struct in_addr
and use inet_ntoa()
("Internet address to ASCII string"):
#include <arpa/inet.h>
struct in_addr addr;
addr.s_addr = htonl(0x0a010203); // s_addr must be in network byte order
char *s = inet_ntoa(addr); // --> "10.1.2.3"
Note that the string returned by inet_ntoa()
may point to static data that may be overwritten by subsequent calls. That is no problem if it is just printed and then not
used anymore. Otherwise it would be necessary to duplicate the string.