0

I use the code below to get IP address of iPhone

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"
- (NSString *) getIPAddress1;
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)  
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)  
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone  
                NSString *s= [NSString stringWithUTF8String:temp_addr->ifa_name];

                NSLog(@"%@       ---",s);
                if([s isEqualToString:IOS_WIFI] || [s isEqualToString:IOS_CELLULAR] || [s isEqualToString:IOS_VPN])
                {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }

    // Free memory
    freeifaddrs(interfaces); 
    return address; 
}

It worked before, but now it always returns @"error".

I even tried all method mention here

iPhone/iPad/OSX: How to get my IP address programmatically?

but none worked.

Your comments are welcome.

clemens
  • 16,716
  • 11
  • 50
  • 65
arachide
  • 8,006
  • 18
  • 71
  • 134

1 Answers1

0

Try this

#import <ifaddrs.h>
#import <arpa/inet.h>

- (NSString *)getIPAddress { 
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];

                }

            }

            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;

}
clemens
  • 16,716
  • 11
  • 50
  • 65
iAnurag
  • 9,286
  • 3
  • 31
  • 48