how to get ip address of iphone programmatically

ghz 7months ago ⋅ 170 views

I got a webserver up and running in iphone by using Mongoose. But the problem is how can I get the ip address of my iphone/ipad to let the user's know where they can access the server. I found that [NSHost addresses] can do the job but I am developing for app store and this is undocumented method.

Answers

To get the IP address of your iPhone or iPad programmatically in a way that is acceptable for App Store submission, you can use the following approach:

#include <ifaddrs.h>
#include <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) {
            sa_family_t sa_type = temp_addr->ifa_addr->sa_family;
            if (sa_type == AF_INET || sa_type == AF_INET6) {
                // 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;
}

This method retrieves the IP address of the iPhone or iPad's WiFi interface (en0) using the getifaddrs() function. It iterates through the list of interfaces until it finds the WiFi interface, then extracts and returns its IP address.

Keep in mind that this method will return the IP address of the device's WiFi interface, which is typically the IP address that other devices on the same network can use to access your iPhone or iPad's web server. However, if the device is not connected to a WiFi network, or if it's connected via cellular data, this method may not return the correct IP address.