开发者

hexadecimal value of ip into standard format

开发者_开发知识库is there any function in linux to display the value 7d162f7d in the format 125.22.47.125 ie convert the hexadecimal ip address in its standard ip format


You could use something like:

#include <stdio.h>
static char *ipToStr (unsigned int ip, char *buffer) {
    sprintf (buffer, "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 0xff,
        (ip >> 8) & 0xff, ip & 0xff);
    return buffer;
}
int main (void) {
    char buff[16];
    printf ("%s\n", ipToStr (0x7d162f7dU, buff));
    return 0;
}

which produces:

125.22.47.125


The correct function to use for this purpose is

inet_ntop - convert IPv4 and IPv6 addresses from binary to text form

In your case as you seem to be refering to an IPv4 address you have to create a struct in_addr something like that

 struct in_addr addr = { .s_addr = YOURVALUE };

and then you have to call it like that

char addrstr[16] = { 0 };

inet_ntop(AF_INET, &addr, addrstr, sizeof(struct in_addr));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜