4

I need to resolve an IP address from a hostname in iOS. I know this is trivial using NSHost, however NSHost resolution capability seems to only work on OSX.

Thanks in advance.

Slappy
  • 4,042
  • 2
  • 29
  • 41
  • please checked out this link may be helped you........ [http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone](http://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone) – Vikas S Singh Aug 07 '12 at 11:48
  • That gets the ip address of the iOS device, nothing to do with the question. – djunod Apr 26 '16 at 18:09

1 Answers1

14

Like this:

struct hostent *host_entry = gethostbyname("stackoverflow.com");
char *buff;
buff = inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));

buff variable now contain an ip address...

Tutankhamen
  • 3,532
  • 1
  • 30
  • 38
  • 3
    Great answer. Thank you. However syntax like this makes baby kittens cry. Why C people have to make everything so cryptic is beyond me. Seriously, hostent as a structure... would it have killed them to put an additional -ry at the end? – Slappy Aug 10 '12 at 12:54
  • 1
    Actually, this code looks "easy to read" for me and I never thought that it can be "cryptic" for somebody. BTW, when I saw objective C code - it was very crypty for me too, but not fo long ;) – Tutankhamen Aug 16 '12 at 00:08
  • When using the code above, my app fails to compile with a warning on the line buff = ... "Dereferencing pointer to incomplete type". Any Idea how to fix this? – AddisDev Jul 18 '13 at 14:31
  • 1
    For people who want to use this solution, remember to include these two header files: #include #include – CodeBrew Mar 11 '14 at 15:47
  • 1
    `inet_ntoa` [is not IPv6 compatiable.](https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/UnderstandingandPreparingfortheIPv6Transition/UnderstandingandPreparingfortheIPv6Transition.html). Use `inet_ntop` instead. [This link](http://linux.die.net/man/3/inet_ntop) said `inet_ntoa` considered to be deprecated. – AechoLiu Jun 22 '16 at 08:58