在iPhone中查找IP地址 [英] Find IP address in iphone

查看:155
本文介绍了在iPhone中查找IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序中找到IP地址。我能找到它。但是,问题是,它在iphone os 2.0左右起作用。但是,在iphone os 3.0中它给了我一个警告:

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)

我正在使用此代码,它适用于os 2.0版。

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

}

如何查找IP地址在iphone os 3.0或更高版本的OS版本?

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

提前致谢。

推荐答案

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

这篇关于在iPhone中查找IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆