在 iPhone 中查找 IP 地址

8

我想在一个应用程序中找到IP地址。我能够找到它。但是问题是,在iPhone OS 2.0或更早版本中可以正常工作。但是,在iPhone OS 3.0中,它会给我一个警告:

warning: no '+currentHost' method found

warning: (Messages without a matching method signature)

我正在使用这段代码,在操作系统版本为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]; 

如何在iPhone OS 3.0或更高版本中查找IP地址?

提前感谢。


最简单的方法(在我看来)是从网站获取外部IP,而不是查询接口。 - Rev316
8个回答

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

不错的解决方案。看起来是最好的一个。 - Dani Pralea

4

将此脚本放置在运行PHP的Web服务器上:

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

在设备上调用此函数:

NSURL *scriptURL = [[NSURL alloc] initWithString:@"http://yourserver.com/script.php"]; 
NSString *ip = [NSString stringWithContentsOfURL: scriptURL encoding:NSASCIIStringEncoding error:nil];

很好,但没有互联网连接就无法工作。而且这有点违背了它的目的,因为通常你想要本地IP地址。 - Dani Pralea

4
据我所知,只有一种hacky的方法可以实现。你需要打开一个套接字并使用POSIX函数获取其地址。以下是我用于此的代码: http://iphonesdksnippets.com/post/2009/09/07/Get-IP-address-of-iPhone.aspx [NSHost currentHost]也可以工作,但它已经被苹果弃用,并被视为“私有API”,因此你将无法在App Store上提交你的应用程序。

IPv6怎么样?有没有关于如何检索它的代码示例? - Oded Regev

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

使用此命令获取您的IP地址

如果出现任何错误,请使用

#include <ifaddrs.h>
#include <arpa/inet.h>

1
我在我的 iPad3 上使用 en0 返回了 127.0.0.1,我不得不使用 en1... 不确定这个修复是否是永久的... - Soup

1

还有一种获取IP地址的方法,那就是全局IP。

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

以上网站将为您提供全球IP地址。只需将其放入您的代码中,无论何时使用IP地址,都可获取使用您的应用程序的用户的位置,因为这提供了全球IP地址。


1

你应该看一下这个好项目: uidevice-extension

特别是this class

在你的项目中导入UIDevice-Reachability.h,然后尝试使用其中一个命令:

NSString *myIp = [UIDevice localIPAddress];
NSString *myIp = [UIDevice localWiFiIPAddress];
NSString *myIp = [UIDevice whatismyipdotcom]; // is using @aamritrao solution

@Nikita P,你需要导入UIDevice-Reachability.m类,然后就可以调用那些函数了。是的,它们是公共的。 - Martin Magakian
谢谢。我只想知道我是否可以在应用商店应用中使用它们。 - Nikita P
由于此类仅使用公共函数,您可以在应用商店上使用它们。 - Martin Magakian

1
获取IP地址有点取巧。你确定不能使用每个iPhone独有且可以通过公共API轻松检索的设备ID(UDID)吗? [UIDevice currentDevice].uniqueIdentifier

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接