8

I want to find IP address in an application. I am able to find it. But, problem is, it works fins in iphone os 2.0 or so. But, in iphone os 3.0 it is giving me a warning:

warning: no '+currentHost' method found

warning: (Messages without a matching method signature)

I am using this code, and it works fine with os version 2.0.

-(NSString*)getAddress {
char iphone_ip[255];
strcpy(iphone_ip,"127.0.0.1"); // if everything fails
NSHost* myhost = [NSHost currentHost];
if (myhost)
{
    NSString *ad = [myhost address];
    if (ad)
        strcpy(iphone_ip,[ad cStringUsingEncoding: NSISOLatin1StringEncoding]);
}
return [NSString stringWithFormat:@"%s",iphone_ip]; 

}

How to find IP address in iphone os 3.0 or greater os version?

Thanks in advance.

Anthony
  • 36,459
  • 25
  • 97
  • 163
Ruchir Shah
  • 898
  • 3
  • 13
  • 31
  • The easiest (IMHO) is just to fetch the external IP from a website, rather then query the interface. – Rev316 Mar 14 '10 at 21:05

8 Answers8

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

// retun the host name
+ (NSString *)hostname
{
    char baseHostName[256]; 
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '\0';

#if !TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
    return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}

// return IP Address
+ (NSString *)localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}
4

Put this script on a web server running PHP:

<?php
$ip = getenv("REMOTE_ADDR");
echo $ip;
?>

Call this on the device:

NSURL *scriptURL = [[NSURL alloc] initWithString:@"http://yourserver.com/script.php"]; 
NSString *ip = [NSString stringWithContentsOfURL: scriptURL encoding:NSASCIIStringEncoding error:nil];
Erik
  • 2,138
  • 18
  • 18
  • nice, but it doesn't work without an internet connection. and it's kinda against the purpose, since you normally want the local ip address – Dani Pralea Oct 15 '13 at 20:28
4

As far as I know there is only one hacky way to do that. You basically open a socket and get its address using POSIX functions. Here is the code I used for this:

http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx

[NSHost currentHost] will also work, but it is deprecated and considered a "Private API" by Apple, so you won't be able to submit your application to App Store.

Wicharek
  • 192
  • 1
  • 6
3
- (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
        // it may also be en1 on your ipad3.
            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; 
}

Use this to get your IP

If any errors Please use

#include <ifaddrs.h>
#include <arpa/inet.h>
Soup
  • 1,699
  • 15
  • 30
aamritrao
  • 181
  • 10
  • 1
    `en0` returned `127.0.0.1` for me on my ipad3, I had to use `en1`... Not sure how permanent that fix is... – Soup Apr 26 '12 at 17:30
1

You should have a look to this good project: uidevice-extension

Specialy this class

Import UIDevice-Reachability.h in your project then try with one of those commands:

NSString *myIp = [UIDevice localIPAddress];
NSString *myIp = [UIDevice localWiFiIPAddress];
NSString *myIp = [UIDevice whatismyipdotcom]; // is using @aamritrao solution
Flexo
  • 87,323
  • 22
  • 191
  • 272
Martin Magakian
  • 3,746
  • 5
  • 37
  • 53
1

Getting the IP address is a bit hacky. Are you sure you couldn't live with the device ID (UDID) that is unique to each iPhone and can be retrieved easily via the public API ?

[UIDevice currentDevice].uniqueIdentifier

yonel
  • 7,855
  • 2
  • 44
  • 51
1

There is one more way to get the IP address and that too Global IP

NSString*  ip=@"http://www.whatismyip.org/";
NSURL *url = [[NSURL alloc] initWithString:ip]; 
NSString *ans = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(@"%@",ans);

The above site will give you the Global IP. Just put this in your code and use the IP address where ever you want and also get the location of the user using your app as this gives global IP.

aamritrao
  • 181
  • 10
0
bool success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct sockaddr_dl *dlAddr;
const uint8_t *base;
int i;

success = getifaddrs(&addrs) == 0;
if (success) {
    cursor = addrs;
    while (cursor != NULL) {
        if ( (cursor->ifa_addr->sa_family == AF_LINK)
            && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type ==IFT_ETHER)
            ) {
            dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
            //      fprintf(stderr, " sdl_nlen = %d\n", dlAddr->sdl_nlen);
            //      fprintf(stderr, " sdl_alen = %d\n", dlAddr->sdl_alen);
            base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
            printf(" MAC address ");
            for (i = 0; i < dlAddr->sdl_alen; i++) {
                if (i != 0) {
                    printf(":");
                }
                printf("%02x", base[i]);
            } 
            printf("\n");
        }
        cursor = cursor->ifa_next;
    }
}
martyman
  • 867
  • 8
  • 14