(This is a work in progress. I wonder if someone could to improve it)
in Objective C, it's easy to resolve a hostname with NSHost.
[[NSHost hostWithName:@"www.google.com"] address]
Sadly iOS (iPhone) contains only a private version of NSHost.
I found many ways of doing this with other Objects or methods, but all of them got only IPv4 addresses in the results. So here is for the moment the only efficient method I have found.
I first tried to use the asynchronous CFHostStartInfoResolution as did bdunagan, but failed to a开发者_如何学Godapt it to IPv6.
Some of you will appreciate to get a method working, so here is one, but if you know a way which would be Asynchronous I would appreciate to learn about it... cause for the moment I use a Popup to alert about the next freeze that could occur with slow cellular connection
/**
Give the IPs corresponding to a Hostname
Sometime only 1 IPv4 is shown even if there's more.
Sometime only 1 IPv6 is shown even if there's more.
Certainly due to iOS Memory optimisation when locally cached
@author Christian Gonzalvez, http://wiki.gonzofamily.com
@param hostName A hostname
@return an Array of NSString of all the corresponding IP addresses. The first
is the Canonical name, the following are IPs (all NSString)
*/
+ (NSArray *)addressesForHostname:(NSString *)hostname
{
const char* hostnameC = [hostname UTF8String];
struct addrinfo hints, *res;
struct sockaddr_in *s4;
struct sockaddr_in6 *s6;
int retval;
char buf[64];
NSMutableArray *result; //the array which will be return
NSMutableArray *result4; //the array of IPv4, to order them at the end
NSString *previousIP = nil;
memset (&hints, 0, sizeof (struct addrinfo));
hints.ai_family = PF_UNSPEC;//AF_INET6;
hints.ai_flags = AI_CANONNAME;
//AI_ADDRCONFIG, AI_ALL, AI_CANONNAME, AI_NUMERICHOST
//AI_NUMERICSERV, AI_PASSIVE, OR AI_V4MAPPED
retval = getaddrinfo(hostnameC, NULL, &hints, &res);
if (retval == 0)
{
if (res->ai_canonname)
{
result = [NSMutableArray arrayWithObject:[NSString stringWithUTF8String:res->ai_canonname]];
}
else
{
//it means the DNS didn't know this host
return nil;
}
result4= [NSMutableArray array];
while (res) {
switch (res->ai_family){
case AF_INET6:
s6 = (struct sockaddr_in6 *)res->ai_addr;
if(inet_ntop(res->ai_family, (void *)&(s6->sin6_addr), buf, sizeof(buf))
== NULL)
{
NSLog(@"inet_ntop failed for v6!\n");
}
else
{
//surprisingly every address is in double, let's add this test
if (![previousIP isEqualToString:[NSString stringWithUTF8String:buf]]) {
[result addObject:[NSString stringWithUTF8String:buf]];
}
}
break;
case AF_INET:
s4 = (struct sockaddr_in *)res->ai_addr;
if(inet_ntop(res->ai_family, (void *)&(s4->sin_addr), buf, sizeof(buf))
== NULL)
{
NSLog(@"inet_ntop failed for v4!\n");
}
else
{
//surprisingly every address is in double, let's add this test
if (![previousIP isEqualToString:[NSString stringWithUTF8String:buf]]) {
[result4 addObject:[NSString stringWithUTF8String:buf]];
}
}
break;
default:
NSLog(@"Neither IPv4 nor IPv6!");
}
//surprisingly every address is in double, let's add this test
previousIP = [NSString stringWithUTF8String:buf];
res = res->ai_next;
}
}else{
NSLog(@"no IP found");
return nil;
}
return [result arrayByAddingObjectsFromArray:result4];
}
NB: I noticed that most of the time only 1 IPv6 is returned, I suspect it's due to iOS Memory optimisation when locally cached. if you run this method again and again, sometime you have 3 IPv6, but then you have only 1 IPv4.
If you want a method to run on a background thread, the simplest way is to use performSelectorInBackground:withObject:
; this is an instance method of NSObject
, so any object can use it without any extra work (including, interestingly enough, class objects, which is good in this case because this is a class method):
[[self class] performSelectorInBackground:@selector(addressesForHostName:)
withObject:theHostName];
Inside the method, you will need to set up an autorelease pool for the thread. You will also need some kind of callback method set up to get the return value back to your main thread. Make sure that you don't try to do any GUI activity on the background thread. It's only safe to do that on the main thread.
+ (NSArray *)addressesForHostname:(NSString *)hostname
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Do your stuff...
// Wait until done to allow memory to be managed properly
// If we did not do this, the array might be deallocated
// before the main thread had a chance to retain it
[self performSelectorOnMainThread:@selector(addressesCallback:)
withObject:[result arrayByAddingObjectsFromArray:result4]
waitUntilDone:YES];
// Inside a class method, self refers to the class object.
[pool drain];
}
If you were not on the main thread to begin with, or if you needed more control, you could also look into NSOperation
, which is more powerful and therefore requires more work. It's still easier than explicit thread management, though!
Hope that solves your problem. It sounded like you have this method doing what you need, you just need it to not block the main thread.
thanks to Josh I could do it, but here is what I had to do :
Instead of calling directly
self.ipAddressesString = [CJGIpAddress addressesForHostname:@"www.google.com"];
I call
[self resolveNow:@"www.google.com"];
And create 3 new methods:
- (void)resolveNow:(NSString *)hostname
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self performSelectorInBackground:@selector(hostname2ipAddresses:)
withObject:hostname];
}
- (void)hostname2ipAddresses:(NSString *)hostname
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//Here is my previous lonely line !! safely started in an other thread
self.ipAddressesString = [CJGIpAddress addressesForHostname:hostname];
[self performSelectorOnMainThread:@selector(resolutionDidFinish)
withObject:nil
waitUntilDone:YES];
[pool drain];
}
- (void)resolutionDidFinish
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//My STUFF with self.ipAddressesString (now filled)
}
Edit: In practice I use all of that in a Model, so I had a crash when I close the View before the end of the resolution
So in the view I added in dealloc what is necessary to avoid a crash
- (void)dealloc
{
self.model.delegate = nil;
[super dealloc];
}
Then - in the model - I test delegate before doing anything with it.
精彩评论