在iOS中从URL确定IP地址

7

我需要在iOS应用程序中从CDN的URL获取IP地址。通过长时间的堆栈搜索,我已经确定了以下方法:

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

然而,当使用这段代码片段时,我的应用程序无法编译,并出现以下警告:“dereferencing pointer to incomplete type”。

我对结构体一无所知,也不知道如何解决这个问题。有什么建议吗?

我还尝试过:

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

但结果仍然是同样的警告。
3个回答

6
这里是将URL主机名转换为IP地址的Swift 3.1版本。
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)
}

5
也许这个函数能够正常工作?
#import <netdb.h>
#include <arpa/inet.h>

- (NSString*)lookupHostIPAddressForURL:(NSURL*)url
{
    // Ask the unix subsytem to query the DNS
    struct hostent *remoteHostEnt = gethostbyname([[url host] UTF8String]);
    // Get address info from host entry
    struct in_addr *remoteInAddr = (struct in_addr *) remoteHostEnt->h_addr_list[0];
    // Convert numeric addr to ASCII string
    char *sRemoteInAddr = inet_ntoa(*remoteInAddr);
    // hostIP
    NSString* hostIP = [NSString stringWithUTF8String:sRemoteInAddr];
    return hostIP;
}

谢谢您的回答。不幸的是,此代码段无法通过编译器并出现以下警告信息:“对不完整类型的指针进行解除引用”。出现问题的代码行为:struct in_addr *remoteInAddr = … 也许有什么地方漏掉了吧?也许是少了某个库文件的引用? - AddisDev
你的函数完美运行,只要加上正确的导入语句,就像上面选择的答案一样。真希望我能选择两个正确的答案。 - AddisDev
真遗憾!我会添加正确的语句作为参考。 - apollosoftware.org

5

我使用以下include语句编译该代码时没有遇到任何问题:

#import <netdb.h>
#include <arpa/inet.h>

D80,你太棒了!我意识到我漏掉了一个导入语句,而你指引了我正确的方向。 - AddisDev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接