Powered By Blogger

Wednesday, May 2, 2012

How to get device IPAddess in iPhone SDK?

 Hello friends,
Here is the code which helps to get the Local IPAddress of an iOS device.

#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];
}


If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati
 

No comments:

Post a Comment