如何获得外部ip在目标c [英] how to get the external ip in objective c

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

问题描述



我找到这个:

   - (NSString *)getIPAddress 
{
NSString * address = @error;
struct ifaddrs * interfaces = NULL;
struct ifaddrs * temp_addr = NULL;
int success = 0;

//检索当前接口 - 成功时返回0
success = getifaddrs(& interfaces);
if(success == 0)
{
//循环通过链接的接口列表
temp_addr = interfaces;
while(temp_addr!= NULL)
{
if(temp_addr-> ifa_addr-> sa_family == AF_INET)
{
//检查接口是否en0这是iphone上的wifi连接
if([[NSString stringWithUTF8String:temp_addr-> ifa_name] isEqualToString:@en0])
{
//从C字符串获取NSString
address = [NSString stringWithUTF8String:inet_ntoa((struct sockaddr_in *)temp_addr-> ifa_addr) - > sin_addr)];
}
}

temp_addr = temp_addr-> ifa_next;
}
}

//可用内存
freeifaddrs(interfaces);

返回地址;
}

但问题是他给我这个ip
10.0。 0.1



谢谢

解决方案

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



对于您可以使用的URL:
http://www.whatismyip.com/m/ mobile.asp

http://checkip.dyndns.com/



只需解析返回数据,并拥有外部IP地址。


i looked for some code that will help me to get the ip that the iphone connect with.

i find this one:

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

but the problem is that he get me this ip 10.0.0.1

there is any article\code about getting the external ip.

thank you

解决方案

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

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

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

这篇关于如何获得外部ip在目标c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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