0

I need to read my iOS device's Wifi address. But the code I've tried is failing on Simulator and on iPad 2 / v6.1.3

I'm working in Titanium, so first I tried Titanium.Platform.address. That comes back undefined.

Then I started working in Objective C. But this function is also failing to get the WiFi IP. I know that WiFi is on because the internet works and my networking project works if I manually enter the device's address.

- (id)networkAddress
{
    NSLog(@"[INFO] getting network IP");

    BOOL success;
    struct ifaddrs * addrs;
    const struct ifaddrs * cursor;

    success = getifaddrs(&addrs) == 0;
    if (success) {

        NSLog(@"[INFO] getifaddrs() success");

        cursor = addrs;
        while (cursor != NULL) {
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0) // this second test keeps from picking up the loopback address
            {
                NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                if ([name isEqualToString:@"en0"]) { // found the WiFi adapter
                    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                }
            }

            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return NULL;
}

What can prevent me from reading the WiFi IP address?

Joe Beuckman
  • 2,264
  • 2
  • 24
  • 63
  • How is that function failing (i.e. what is the value of `success`), and is it still failing if you remove the check for `"en0"` in the interface name? – phihag Mar 31 '13 at 22:29
  • 1
    I added two log traces. The first gets called - it verifies that the function has been called. But the second NSLog never happens. getifaddrs(&addrs) is not returning 0. – Joe Beuckman Mar 31 '13 at 22:37
  • 2
    Check `errno` if `getifaddrs()` failed. – Martin R Mar 31 '13 at 22:40
  • errno = 6 ENXIO No such device or address. Input or output on a special file referred to a device that did not exist, or made a request beyond the limits of the device. This error may also occur when, for example, a tape drive is not online or no disk pack is loaded on a drive. – Joe Beuckman Mar 31 '13 at 22:59
  • This is working for me: http://stackoverflow.com/questions/6530322/fetching-ip-address-of-router-to-which-iphone-is-connected/6530703#6530703 – Joe Beuckman Mar 31 '13 at 23:35

0 Answers0