Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to get the IP address of a CDN from it's URL in an iOS app. From a long stack search, i've determined a method for doing this with the following:

struct hostent *host_entry = gethostbyname("stackoverflow.com");
char *buff;
buff = inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));
// buff is now equal to the IP of the stackoverflow.com server

However, when using this code snippet, my app fails to compile and presents this warning: "dereferencing pointer to incomplete type"

I have no knowledge of structs and I do not know how to fix this. Any suggestions?

I also tried:

#include <ifaddrs.h>
#include <arpa/inet.h>

But the result is the same warning.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
601 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is a Swift 3.1 version of converting a URL hostname to IP address.

import Foundation
private func urlToIP(_ url:URL) -> String? {
  guard let hostname = url.host else {
    return nil
  }

  guard let host = hostname.withCString({gethostbyname($0)}) else {
    return nil
  }

  guard host.pointee.h_length > 0 else {
    return nil
  }

  var addr = in_addr()
  memcpy(&addr.s_addr, host.pointee.h_addr_list[0], Int(host.pointee.h_length))

  guard let remoteIPAsC = inet_ntoa(addr) else {
    return nil
  }

  return String.init(cString: remoteIPAsC)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...