5

我目前正在使用此代码

    NSHost *host = [NSHost hostWithAddress:hostname];
if (host == nil) {
    host = [NSHost hostWithName:hostname];
    if (host == nil) {
        [self setMessage:@"Invalid IP address or hostname:"];
        return;
    }
}

为我正在开发的网络应用程序检索我的 IP 地址,但是我知道 NSHost 是一个私有 API,将被拒绝。任何人都可以帮助我在不使用 NSHost 的情况下使用此代码产生相同的结果吗?我不确定从哪里开始。

编辑:

按照下面看起来该死的近乎完美的建议,我已将此代码添加到我的应用程序中以代替上面的代码

    Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *hostname = @"www.apple.com";
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
if (hostRef) {
    result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
    if (result == TRUE) {
        addresses = CFHostGetAddressing(hostRef, &result);
    }
}
if (result == TRUE) {
    NSLog(@"Resolved");
} else {
    NSLog(@"Not resolved");
}

我已经删除了第 4 行(因为我已经从其他地方获得了这些信息),但是我收到了基于 CFHostRef 未声明的错误。我将如何解决这个问题?这似乎是我唯一的大障碍,因为其他错误只是基于之后无法看到 hostRef。编辑:从头开始,我也未声明 kCFHostAddresses。

4

3 回答 3

6

您可以使用 CFHost 来实现相同的目的。CFHost Reference的顶部是用于查找的食谱。

下面的代码做了非常非常基本的同步解析(就像你上面的 NSHost 一样)。请注意,您不想这样做,因为它可能会使您的应用程序无响应,因为它在解决或超时命中之前不会返回。

改用异步查找(CFHostSetClient 和 CFHostScheduleWithRunLoop,如上面的 CFHost 文档中所述)。此外,根据您的计划,您可能需要考虑使用可达性 API。查看 iPhone 开发者网站上关于网络的 WWDC 会议。

Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *hostname = @"www.apple.com";
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)hostname);
if (hostRef) {
    result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
    if (result == TRUE) {
        addresses = CFHostGetAddressing(hostRef, &result);
    }
}
if (result == TRUE) {
    NSLog(@"Resolved");
} else {
    NSLog(@"Not resolved");
}

// Don't forget to release hostRef when you're done with it
于 2010-08-08T13:29:37.397 回答
0

看看这个:http ://blog.zachwaugh.com/post/309927273/programmatically-retrieving-ip-address-of-iphone

于 2010-08-08T13:32:45.660 回答
-3

http://developer.apple.com/iphone/library/qa/qa2009/qa1652.html

通过开发人员支持系统得到了一个很好的小答案,这非常有效。

于 2010-08-13T09:11:01.873 回答