如何在Objective-C中获取外部IP [英] How to get the external ip in Objective-C

查看:98
本文介绍了如何在Objective-C中获取外部IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一些代码,这些代码将帮助我获取与iPhone连接的IP.

I looked for some code that will help me to get the ip that the iPhone connect with.

我找到了这个:

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

但是问题是他让我获得了这个IP 10.0.0.1

but the problem is that he get me this ip 10.0.0.1

如何获取外部IP?

推荐答案

从代码获取Internet ip地址的最简单方法是使用

The easiest way to get your internet ip address from code is to use NSURLConnection.

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

For the URL you can use: http://www.whatismyip.com/m/mobile.asp or http://checkip.dyndns.com/

只需解析返回数据,您就拥有外部IP地址.

Just parse the return data and you have your external ip address.

这篇关于如何在Objective-C中获取外部IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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