How to get my IP address programmatically on iOS/macOS?

ios get ip address programmatically swift 4
ios get external ip address swift
iphone cellular network ip address
nshost ios
swift5 get ip address
pdp_ip
swift get network information
ifaddrs swift

I would like to obtain my iPad's IP address programmatically. How can I query the networking subsystem to find out what my IPv4 (and IPv6) addresses are?

PS: Can I disable IPv6 somehow?

The following code finds all IPv4 and IPv6 addresses on an iOS or OSX device. The first getIPAddress method acts more or less as the older code in this answer: you can prefer either one or the other type address, and it always prefers WIFI over cellular (obviously you could change this).

More interestingly it can return a dictionary of all addresses found, skipping addresses for not up interfaces, or addresses associated with loopback. The previous code as well as other solutions on this topic will not properly decode IPv6 (inet_ntoa cannot deal with them). This was pointed out to me by Jens Alfke on an Apple forum - the proper function to use is inet_ntop (look at the man page, and or refer to this inet_ntop article also provided by Jens.

The dictionary keys have the form "interface" "/" "ipv4 or ipv6".

#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
//#define IOS_VPN       @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

- (NSString *)getIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ?
                            @[ /*IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6,*/ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
                            @[ /*IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4,*/ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;

    NSDictionary *addresses = [self getIPAddresses];
    NSLog(@"addresses: %@", addresses);

    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
        {
            address = addresses[key];
            if(address) *stop = YES;
        } ];
    return address ? address : @"0.0.0.0";
}

- (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];

    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}

EDIT1: Code updated on May 16, 2014 (bug pointed out by lhunath, see comments). Loopback addresses now returned, but its easy for you to uncomment the test to exclude them yourself.

EDIT2: (by some unknown person): Improved further March 13, 2015: In case the user uses a VPN (regardless over WiFi or Cellular), the previous code would have failed. Now, it works even with VPN connections. VPN connections are given precedence over WiFi and Cell because that's how the device handles it. This should even work for Macs as the VPN connection on a Mac is also using IF utun0 but not tested.

EDIT3: (9/8/2016) Given the problems experienced by @Qiulang (see comments) with the VPN code (which someone else added), I've commented it out. If anyone knows definitively how to specify a user VPN please chime in with a comment.

Can we access device IP address in…, WWAN — See below. My iOS device on the road just has WWAN. My cellular provider currently hands out NATed IPv4 addresses, where one address is shared  To find your internal IP address on a newer Mac, first click on the Apple icon on the upper-left corner of the screen. From here, click on “System Preferences…” in the drop down menu that appears. Then, click the “Network” icon in the box that opens.

In your implementation file .m ,

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



// Get IP Address
- (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;

} 

abhimuralidharan/IPAddressTest: Code to get current local , Code to get current local ip address (cellullar and wifi local ip) in objective -C, Refer: /7072989/iphone-ipad-osx-how-to-get-my-ip-address-programmatically. From the Apple menu pull down “System Preferences” Click on the “Network” preference pane Your IP address will be visible to the right, as indicated in the screenshot below Your IP address is the number listed, in the above case it is 192.168.0.100

Many existing solutions only consider wireless interfaces, which won't work for wired connections via an Ethernet adapter (ie. no Wifi or 3G); see this more recent solution which considers IP addresses obtained through wired interfaces as well.

iPad: How to get IP address programmatically WIRED (not via wireless)

How do I find my IP address on the iPhone?, How do I find my LTE IP address on my iPhone? I know how to get the IP address, via en0 interface, seen here: iPhone/iPad/OSX: How to get my IP address programmatically? But now I'm implementing an ethernet connection to the LAN using the Lightning to USB 3 Camera Adapter in order to connect to the internet without Wifi in 9.3, so the above solution can't resolve the IP address without the

Get IP address using Swift 3:

func getIPAddress() -> String {
    var address: String = "error"

    var interfaces: ifaddrs? = nil

    var temp_addr: ifaddrs? = nil
    var success: Int = 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 != nil {
            if temp_addr?.ifa_addr?.sa_family == AF_INET {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if (String(utf8String: temp_addr?.ifa_name) == "en0") {
                    // Get NSString from C String
                    address = String(utf8String: inet_ntoa((temp_addr?.ifa_addr as? sockaddr_in)?.sin_addr))
                }
            }
            temp_addr = temp_addr?.ifa_next
        }
    }
        // Free memory
    freeifaddrs(interfaces)
    return address
}

Swift - Get device's WIFI IP Address, in Settings/WiFi, then tap on the i next to the network name. It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift. As Apple stated: In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead.

The current solution doesn't return the en0 device on OS X, the following code uses the System Configuration Framework to get the interfaces then uses standard C functions to get the IP address.

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/ioctl.h>
#include <net/if.h>
#define IFT_ETHER 0x6

#include <SystemConfiguration/SCDynamicStore.h>

+(void)getInterfaces
{
    SCDynamicStoreRef storeRef = SCDynamicStoreCreate(NULL, (CFStringRef)@"FindCurrentInterfaceIpMac", NULL, NULL);
    CFPropertyListRef global = SCDynamicStoreCopyValue (storeRef,CFSTR("State:/Network/Interface"));
    id primaryInterface = [(__bridge NSDictionary *)global valueForKey:@"Interfaces"];

    for (NSString* item in primaryInterface)
    {
        if(get_iface_address([item UTF8String]))
        {
            NSString *ip = [NSString stringWithUTF8String:get_iface_address([item UTF8String])];
            NSLog(@"interface: %@ - %@",item,ip);
        } else
            NSLog(@"interface: %@",item);
    }
}

static char * get_iface_address (char *interface)
{
    int sock;
    uint32_t ip;
    struct ifreq ifr;
    char *val;

    if (!interface)
        return NULL;

    /* determine UDN according to MAC address */
    sock = socket (AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        perror ("socket");
        return NULL;
    }

    strcpy (ifr.ifr_name, interface);
    ifr.ifr_addr.sa_family = AF_INET;

    if (ioctl (sock, SIOCGIFADDR, &ifr) < 0)
    {
        perror ("ioctl");
        close (sock);
        return NULL;
    }

    val = (char *) malloc (16 * sizeof (char));
    ip = ((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr.s_addr;
    ip = ntohl (ip);
    sprintf (val, "%d.%d.%d.%d",
             (ip >> 24) & 0xFF, (ip >> 16) & 0xFF, (ip >> 8) & 0xFF, ip & 0xFF);

    close (sock);

    return val;
}

How to get the Mac address and IP address of the iOS device using , How do I find the IP address of a device in Swift? Enter your desired IP address into the field labeled “IPv4 Address.” You can take your current IP address and change the last part of the number. For example, your current IP address is "10.0.1.8," so your new IP address can be something like "10.0.1.129."

Programmatically retrieving IP Address of iPhone • Zach Waugh, : String? var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil if getifaddrs(&ifaddr) == 0 { var ptr = ifaddr while ptr != How to Find your LAN IP address via the Mac OS X GUI You can retrieve the LAN IP address of any Mac through system settings, here’s where to look: Open “System Preferences” from the Apple menu

How to Get Your Own IP Address Programmatically, How do I get the Mac address and IP address of the iOS device using the Swift programming? What are some simple steps I can take to protect my privacy online? of your iPhone refer to how to get ip address of iphone programmatically. The following code finds all IPv4 and IPv6 addresses on an iOS or OSX device. The first getIPAddress method acts more or less as the older code in this answer: you can prefer either one or the other type address, and it always prefers WIFI over cellular (obviously you could change this).

How to get user external IP and Geolocation Info Programmatically , The iPhone SDK provided no simple way to get the IP Address for the wifi connection. Here's an Objective-C method to retrieve the IP address of the wifi This will also work in Mac OS X since the iPhone OS and Mac OS X  Get Local Wifi IP address on iOS and Android. This Gist provide the function to retrieve the local IP address of the device when connected to the wifi. iOS. No permission is required from the user to access the information.

Comments
  • In regards to your 'PS' above, please do not programmatically disable IPv6 on somebody's device. It's just plain rude.
  • You can't disable IPv6. It is mandatory. In fact, your iOS app must support IPv6.
  • how often addr gets NULL? my users occasionally get NULL. do you know whats possible reasons?
  • I'm using only AF_INET to check. could be this?
  • I don't know, but it is for sure possible your users could be on an IPV6 network.
  • This should be the "right" answer as it is complete with 3G. Thanks for the update.
  • I don't think this works correctly with IPv6. The inet_ntoa function takes an IPv4 address, so in the case where sa_type == AF_INET6, you're taking the IPv6 address and type-casting it to IPv4 and turning that to a string (basically from the high 32 bits of the 128-bit address.)
  • No en0 interface appears in the interfaces list, so just returns error. Not sure if something has changed but definitely not working for me on iOS 5.x
  • If you look below you will find some slightly modified code that returns the cell (3G) address if WIFI is off.
  • The following code gives the IPv4 address of en0 only. What about IPv6? Can someone give a code sample on how to retrieve it?
  • This one doesn't find ip address when device is not connected to wifi, but to cellluar network