The weirdest solution for finding a computer's IP address I've read about is to run a NSTask that executes a perl script that in turn calls curl that retrieves the content of www.whatismyip.org.
I'm pasting the code I use below, in the hope that it will be useful to others and we won't get Cocoa applications that open an HTTP connection to figure out what the local IP address is.
Note: it is assumed that hostname points to a previously allocated sufficiently large buffer. You can of course use a NSString to make sure you don't get exposed to buffer overflows. Or just replace strcpy with strncpy.
I'm pasting the code I use below, in the hope that it will be useful to others and we won't get Cocoa applications that open an HTTP connection to figure out what the local IP address is.
Note: it is assumed that hostname points to a previously allocated sufficiently large buffer. You can of course use a NSString to make sure you don't get exposed to buffer overflows. Or just replace strcpy with strncpy.
#import <SystemConfiguration/SystemConfiguration.h>
#import <Cocoa/Cocoa.h>
//other stuff here like declaring an actual class interface and implementation
- (char *) getAddressOfPrimaryInterface: (char *) hostname
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int i;
SCDynamicStoreContext context = { 0, (void *)self, NULL, NULL, NULL };
SCDynamicStoreRef dynStore = SCDynamicStoreCreate(
NULL,
(CFStringRef) [[NSBundle mainBundle] bundleIdentifier],
nil,
&context);
NSArray * allKeys;
NSString * primaryInterface;
allKeys = [(NSArray *)SCDynamicStoreCopyKeyList(dynStore, CFSTR("State:/Network/Global/IPv4")) autorelease];
for(i=0; i<[allKeys count]; i++)
{
NSLog(@"Current key: %@, value: %@",
[allKeys objectAtIndex:i],
[(NSString *)SCDynamicStoreCopyValue(dynStore, (CFStringRef)[allKeys objectAtIndex:i]) autorelease]);
NSDictionary * dict = [(NSDictionary *)
SCDynamicStoreCopyValue(dynStore, (CFStringRef)[allKeys objectAtIndex:i]) autorelease];
NSLog(@"PrimaryInterface: %@ value is: %@", [allKeys objectAtIndex:i], [dict objectForKey:@"PrimaryInterface"]);
primaryInterface = (NSString *) [dict objectForKey:@"PrimaryInterface"];
}
allKeys = [(NSArray *)SCDynamicStoreCopyKeyList(dynStore,
CFStringCreateWithFormat(kCFAllocatorDefault,
NULL,
CFSTR("State:/Network/Interface/%@/IPv4"),
primaryInterface)) autorelease];
for(i=0; i<[allKeys count]; i++)
{
NSLog(@"Current key: %@, value: %@",
[allKeys objectAtIndex:i],
[(NSString *)SCDynamicStoreCopyValue(dynStore, (CFStringRef)[allKeys objectAtIndex:i]) autorelease]);
NSDictionary * dict = [(NSDictionary *)
SCDynamicStoreCopyValue(dynStore, (CFStringRef)[allKeys objectAtIndex:i]) autorelease];
NSLog(@"IPv4 interface: %@ value is: %@", [allKeys objectAtIndex:i], [dict objectForKey:@"Addresses"]);
strcpy(hostname, [[[dict objectForKey:@"Addresses"] objectAtIndex:0] cString]);
}
[pool release];
return hostname;
}