美文网首页
iOS 获取本机在局域网中的IP

iOS 获取本机在局域网中的IP

作者: 在下有双 | 来源:发表于2017-09-14 13:49 被阅读0次

    1、添加头文件

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

    2、实现方法

    - (NSString *)localIPAddress
    {
    NSString *localIP = nil;
    struct ifaddrs *addrs;
    if (getifaddrs(&addrs)==0) {
        const struct ifaddrs *cursor = addrs;
        while (cursor != NULL) {
            if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
            {
                //NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
                //if ([name isEqualToString:@"en0"]) // Wi-Fi adapter
                {
                    localIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
                    break;
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    return localIP;
    }
    

    相关文章

      网友评论

          本文标题:iOS 获取本机在局域网中的IP

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