12

I have an IP address stored in in_addr_t and I want to create the corresponding string representation of this data type (e.g. in_addr_t to 10.0.0.1).

How can I do that?

Robb1
  • 4,587
  • 6
  • 31
  • 60
cateof
  • 6,608
  • 25
  • 79
  • 153

3 Answers3

9

Use inet_ntop() - convert IPv4 and IPv6 addresses from binary to text form.

pevik
  • 4,523
  • 3
  • 33
  • 44
James Anderson
  • 27,109
  • 7
  • 50
  • 78
  • inet_ntop takes const void *restrict src as argument. My type is in_addr_t. How can I convert between the two of them? – cateof Sep 22 '10 at 11:08
  • 2
    @cateof: You can simply pass the address of your `in_addr_t` variable as the `src` argument, with `AF_INET` as the `af` argument. – caf Sep 22 '10 at 13:37
  • More recent documentation [here](http://man7.org/linux/man-pages/man3/inet_ntop.3.html) – HappyCactus Sep 07 '17 at 08:39
0
-(NSString*)long2ip:(uint32_t)ip
{
    char str[40];
    struct in_addr myaddr;
    myaddr.s_addr = htonl(ip);
    if (inet_ntop(AF_INET, &myaddr, str, sizeof(str)))
    {
        return [NSString stringWithFormat:@"%s",str];
    }
    else
    {
        return nil;
    }
}
Farhad Malekpour
  • 1,314
  • 13
  • 16
-1

char *inet_ntoa(struct in_addr in);
is the desired function.

bhups
  • 14,345
  • 8
  • 49
  • 57
  • 3
    inet_ntoa() seems to be considered deprecated. – unwind Sep 22 '10 at 10:32
  • 2
    inet_ntoa takes an in_addr that is not the same as inet_addr_t. Please consider changing your answer. – WeGi Jun 20 '14 at 12:28
  • `inet_ntoa` is a non-reentrant functions, because it returns static buffer. So better to use `inet_ntop` instead of `inet_ntoa`. – rashok Nov 29 '17 at 09:37