tags:

views:

63

answers:

2

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

+6  A: 

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
paxdiablo
if you have struct in_addr, you can also use Jens Gustedt suggestion below.
Kedar
+3  A: 

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));
Jens Gustedt
+1 for using standard functions. But you could use `INET_ADDRSTRLEN` instead of '16' for your char array and use a simple `in_addr_t addr = YOURVALUE` instead of a whole structure.
schot
@schot: I am not sure about the `in_addr_t addr = YOURVALUE`. `in_addr_t` in essence is just an integer type, no? When called with `AF_INET` as an argument `inet_ntop` expects `struct in_addr` which at least in theory could have other fields than `s_addr`, and where it mustn't even be the first member.
Jens Gustedt
@Jens I'm a bit unsure myself. But the second argument of `inet_ntop()` is `const void *restrict src`. POSIX says: "The src argument points to a buffer holding an IPv4 address if the af argument is AF_INET, [...]", but does not specify the allowed formats for this buffer.
schot
@schot: well it really seems that this is not well defined in POSIX. Linux definitively has `struct in_addr` and OS X states something bizzaroid as `usually a struct in_addr or some other binary form, in network byte order`.
Jens Gustedt