【发布时间】:2012-03-05 13:33:57
【问题描述】:
在对主机名执行NSURLRequest 时,是否可以获得响应来自的服务器的IP 地址?
NSURL 方法:
- (NSString *)host;
只返回主机名,我认为无法从任何其他 NSURL 方法获取 IP 地址。
也许有一种方法可以在启动 NSURLRequest 之前执行主机查找?
【问题讨论】:
标签: objective-c ios cocoa-touch networking
在对主机名执行NSURLRequest 时,是否可以获得响应来自的服务器的IP 地址?
NSURL 方法:
- (NSString *)host;
只返回主机名,我认为无法从任何其他 NSURL 方法获取 IP 地址。
也许有一种方法可以在启动 NSURLRequest 之前执行主机查找?
【问题讨论】:
标签: objective-c ios cocoa-touch networking
您可以使用系统调用gethostbyname() 来解析主机名,然后使用返回的结构来获取IP 地址。最后一部分请查看inet_ntop()。
示例代码
struct hostent *hostentry;
hostentry = gethostbyname("google.com");
char * ipbuf;
ipbuf = inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0]));
printf("%s",ipbuf);
【讨论】:
我在问一个关于
的问题"如何从 unix\linux 中的主机名获取 IP?"
但是在不同的上下文中发现了这个问题,我猜这不适用于 Unix,如果我错了,请纠正
因为这个问题已经被问过,所以我担心避免问同样的问题,堆栈溢出团队标记为重复。
任务:如何从 unix\linux 中的主机名获取 IP?
Ans:那边的两条指令
例如:
ping -s google.co.in
PING google.co.in: 56 data bytes
64 bytes from dfw06s48-in-f3.1e100.net (216.58.194.99): icmp_seq=0. time=2.477 ms
64 bytes from dfw06s48-in-f3.1e100.net (216.58.194.99): icmp_seq=1. time=1.415 ms
64 bytes from dfw06s48-in-f3.1e100.net (216.58.194.99): icmp_seq=2. time=1.712 ms
例如:
nslookup google.co.in
Server: 155.179.59.249
Address: 155.179.59.249#53
Non-authoritative answer:
Name: google.co.in
Address: 216.58.194.99
【讨论】:
#import <arpa/inet.h>
- (BOOL)resolveHost:(NSString *)hostname {
Boolean result;
CFHostRef hostRef;
CFArrayRef addresses;
NSString *ipAddress = nil;
hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge
CFStringRef)hostname);
CFStreamError *error = NULL;
if (hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, error);
if (result) {
addresses = CFHostGetAddressing(hostRef, &result);
}
}
if (result) {
CFIndex index = 0;
CFDataRef ref = (CFDataRef) CFArrayGetValueAtIndex(addresses, index);
int port=0;
struct sockaddr *addressGeneric;
NSData *myData = (__bridge NSData *)ref;
addressGeneric = (struct sockaddr *)[myData bytes];
switch (addressGeneric->sa_family) {
case AF_INET: {
struct sockaddr_in *ip4;
char dest[INET_ADDRSTRLEN];
ip4 = (struct sockaddr_in *)[myData bytes];
port = ntohs(ip4->sin_port);
ipAddress = [NSString stringWithFormat:@"%s", inet_ntop(AF_INET, &ip4->sin_addr, dest, sizeof dest)];
}
break;
case AF_INET6: {
struct sockaddr_in6 *ip6;
char dest[INET6_ADDRSTRLEN];
ip6 = (struct sockaddr_in6 *)[myData bytes];
port = ntohs(ip6->sin6_port);
ipAddress = [NSString stringWithFormat:@"%s", inet_ntop(AF_INET6, &ip6->sin6_addr, dest, sizeof dest)];
}
break;
default:
ipAddress = nil;
break;
}
}
NSLog(@"%@", ipAddress);
if (ipAddress) {
return YES;
} else {
return NO;
}
}
[self resolveHost:@"google.com"]
【讨论】: