Pages

June 17, 2013

Get my own IP address on iPhone (or iPad, iPod)

What's my IP?
It works on both iOS (iPhone, iPad, iPod) and Mac OS Xcode projects.


/** Returns the local own IP address.

 @return Returns the IP address as string.

 */
+ (NSString *)myIpAddress {
    NSString *address = @"127.0.0.1"; // Default value that means you're probably not connected to a network.
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = getifaddrs(&interfaces); // Retrieve the current interfaces - returns 0 on success.
    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;
}



Download the ready-for-use source file (.m) of Get my own IP address on iPhone (or iPad, iPod)

No comments:

Post a Comment