如何在目标c中获得外部ip

MTA*_*MTA 6 iphone cocoa-touch objective-c ios

我找了一些代码来帮助我获得iphone连接的ip.

我找到了这个:

- (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
                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;
}
Run Code Online (Sandbox Code Playgroud)

但问题是他给我这个ip 10.0.0.1

有任何关于获取外部IP的文章\代码.

谢谢

Bla*_*rog 4

从代码中获取互联网 IP 地址的最简单方法是使用NSURLConnection

对于 URL,您可以使用: http://www.whatismyip.com/m/mobile.asphttp://checkip.dyndns.com/

只要解析返回数据,你就得到了你的外部IP地址。