美文网首页
获取手机ip地址的方法

获取手机ip地址的方法

作者: 老刘_Tony | 来源:发表于2016-11-11 10:45 被阅读0次

    有的需求中需要获取手机的ip地址,下面的函数就能完成这一功能。

    首先要引入两个头文件:

    #include <ifaddrs.h>

    #include<arpa/inet.h>

    然后是获取ip地址的函数实现

    - (NSString*)getPhoneIPAddress

    {

    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"])

    {

    //  C  String 转NSString

    address = [NSStringstringWithUTF8String:inet_ntoa(((structsockaddr_in*)temp_addr->ifa_addr)->sin_addr)];

    }

    }

    temp_addr = temp_addr->ifa_next;

    }

    }

    // 释放内存

    freeifaddrs(interfaces);

    return       address;

    }

    注:该方法只能在真机中运行有效。

    相关文章

      网友评论

          本文标题:获取手机ip地址的方法

          本文链接:https://www.haomeiwen.com/subject/doxryttx.html