Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find IP address in iphone

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.

like image 218
Ruchir Shah Avatar asked Mar 02 '10 06:03

Ruchir Shah


1 Answers

#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];
}
like image 117
Nilesh Prajapati Avatar answered Sep 21 '22 06:09

Nilesh Prajapati