在iOS中确定URL中的IP地址

时间:2013-07-18 14:47:40

标签: objective-c ip hostname

我需要从iOS应用中的URL获取CDN的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

但是,在使用此代码段时,我的应用程序无法编译并显示此警告:“取消引用指向不完整类型的指针”

我不了解结构,我不知道如何解决这个问题。有什么建议吗?

我也尝试过:

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

但结果是同样的警告。

3 个答案:

答案 0 :(得分:5)

使用以下内容编译代码时没有问题:

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

答案 1 :(得分:4)

也许这个功能会起作用?

#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;
}

答案 2 :(得分:4)

以下是将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)
}
相关问题