2

I need to get the ipaddress of an iphone/ipad device,

I used the following code

- (NSString *)getIPAddress
{
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
NSString *wifiAddress = nil;
NSString *cellAddress = nil;
   // retrieve the current interfaces - returns 0 on success
if(!getifaddrs(&interfaces)) {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL) {
        sa_family_t sa_type = temp_addr->ifa_addr->sa_family;
        if(sa_type == AF_INET || sa_type == AF_INET6)
        {
            name = [[NSString stringWithUTF8String:temp_addr->ifa_name] retain];
             addr = [[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] retain]; // pdp_ip0
            if([name isEqualToString:@"en0"])
            {
                // Interface is the wifi connection on the iPhone
                wifiAddress = addr;
                 NSLog(@"address  addr  %@",addr);
            }
            else if([name isEqualToString:@"pdp_ip0"])
            {
                // Interface is the cell connection on the iPhone
                cellAddress = addr;
                 NSLog(@"address  addr  %@",addr);
            }
        }
        temp_addr = temp_addr->ifa_next;
    }
    // Free memory
    freeifaddrs(interfaces);
}

addr = wifiAddress ? wifiAddress : cellAddress;

NSLog(@"address  addr  %@",addr);
return addr ? addr : @"0.0.0.0";
}

It works fine when an application is not universal application.

When i changed the application to universal application it is returning null value as responce

please help me, Thanks in advance

Madhu
  • 2,565
  • 2
  • 25
  • 32
  • I don't understand how changing to universal would break that code?!? – trojanfoe Jan 21 '14 at 14:06
  • Did you try to step through it with the debugger? Is the return value of `getIPAddress` really nil? What are the NSLog outputs? – NoilPaw Jan 21 '14 at 14:11
  • it is returning (null).Like this "address addr (null)" – Madhu Jan 21 '14 at 14:22
  • @Madhu So you are running it on the same device/simulator for both universal and non-universal builds? – trojanfoe Jan 21 '14 at 14:33
  • OK, well this: `|| sa_type == AF_INET6` is wrong as the IPv6 address will be in a different structure to the IPv4 address, so that might be the reason. – trojanfoe Jan 21 '14 at 14:36
  • See this gist for a working example, which was testing under OSX 10.8.5: https://gist.github.com/trojanfoe/8541571 – trojanfoe Jan 21 '14 at 14:56

0 Answers0