Ruc*_*hah 8 iphone ip-address nshost
我想在应用程序中找到IP地址.我能找到它.但是,问题是,它在iphone os 2.0左右工作.但是,在iphone os 3.0中它给了我一个警告:
warning: no '+currentHost' method found
warning: (Messages without a matching method signature)
Run Code Online (Sandbox Code Playgroud)
我正在使用此代码,它与os 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];
Run Code Online (Sandbox Code Playgroud)
}
如何在iphone os 3.0或更高版本的os版本中找到IP地址?
提前致谢.
#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];
}
Run Code Online (Sandbox Code Playgroud)
据我所知,只有一种巧妙的方法可以做到这一点。基本上,您打开一个套接字并使用 POSIX 函数获取其地址。这是我为此使用的代码:
http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx
[NSHost currentHost]也可以使用,但它已被 Apple 弃用并视为“私有 API”,因此您将无法向 App Store 提交您的应用程序。
| 归档时间: |
|
| 查看次数: |
15647 次 |
| 最近记录: |