美文网首页
iOS 获取手机当前所连接的网络的IP地址

iOS 获取手机当前所连接的网络的IP地址

作者: 法库德 | 来源:发表于2018-07-18 11:03 被阅读0次

    1首先要在当前所在的类导入这几个头文件:

    #include

    #include

    #include

    #include

    #import

    2具体代码的实现:

    //获取手机的网络的ip地址

    - (NSString *)getIPAddress

    {

    BOOL success;

    struct ifaddrs * addrs;

    const struct ifaddrs * cursor;

    success = getifaddrs(&addrs) == 0;

    if (success) {

    cursor = addrs;

    while (cursor != NULL) {

    // the second test keeps from picking up the loopback address

    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

    NSLog(@"IP:%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]);

    return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];

    }

    cursor = cursor->ifa_next;

    }

    freeifaddrs(addrs);

    }

    return nil;

    }

    NSLog(@"========11========%@",[self getIPAddress]);

    相关文章

      网友评论

          本文标题:iOS 获取手机当前所连接的网络的IP地址

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