iOS之WiFi IP相关

Posted 善斋书屋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS之WiFi IP相关相关的知识,希望对你有一定的参考价值。

  • Questions

    在[ios实现WIFI传书]中有一个获取IP的步骤
    在此顺带总结一份关于WIFI与IP的常用内容

    1. 设备网络IP地址
    2. WiFi信息
    3. 路由器地址
    4. 本机DNS服务器
    5. 手机的网络IP地址
    6. 进入WiFi设置
  • Code

    • 设备网络IP地址
    // 获取设备网络Ip地址
    + (NSString *)deviceNetIp {
        int sockfd =socket(AF_INET,SOCK_DGRAM,0);
        // if (sockfd < 0) return nil;
        NSMutableArray *ips = [NSMutableArray array];
        int BUFFERSIZE = 4096;
        struct ifconf ifc;
        char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
        struct ifreq *ifr, ifrcopy;
        ifc.ifc_len= BUFFERSIZE;
        ifc.ifc_buf= buffer;
        if(ioctl(sockfd, SIOCGIFCONF, &ifc) >= 0){
            for(ptr = buffer; ptr < buffer + ifc.ifc_len; ){
                ifr = (struct ifreq*)ptr;
                int len =sizeof(struct sockaddr);
                if(ifr->ifr_addr.sa_len > len) {
                    len = ifr->ifr_addr.sa_len;
                }
                ptr +=sizeof(ifr->ifr_name) + len;
                if(ifr->ifr_addr.sa_family != AF_INET)
                    continue;
                if((cptr = (char*)strchr(ifr->ifr_name,\':\')) != NULL)
                    *cptr =0;
                if(strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0)
                    continue;
                memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
                ifrcopy = *ifr;
                ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
                if((ifrcopy.ifr_flags&IFF_UP) == 0)
                    continue;
                NSString *ip = [NSString stringWithFormat:@"%s", inet_ntoa(((struct sockaddr_in*)&ifr->ifr_addr)->sin_addr)];
                [ips addObject:ip];
            }
        }
        close(sockfd);
        NSString *deviceIP = @"";
        for(int i = 0; i < ips.count; i++) {
            if(ips.count > 0) {
                deviceIP = [NSString stringWithFormat:@"%@", ips.lastObject];
            }
        }
        return deviceIP;
    }
    • WiFi信息
    /*
     * 获取wifi信息
     * iOS12以上的版本获取wifi信息,需在中设Capability置Access WIFI Infomation = ON
     * iOS13获取之前需获判断是否同意app适用地理位置信息
     */
    - (void)wifi:(void(^)(NSDictionary *sender))handler {
        if (@available(iOS 13.0, *)) {
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
                // 设置定位权限
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
            } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
                self.manager = [[CLLocationManager alloc] init];
                self.manager.delegate = self;
                [self.manager requestWhenInUseAuthorization];
                self.wifiBlock = handler;
            } else {
                [self fetchWifi:handler];
            }
        } else {
            [self fetchWifi:handler];
        }
    }
    - (void)fetchWifi:(void(^)(NSDictionary *sender))handler {
        NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
        NSDictionary *SSIDInfo;
        for (NSString *interfaceName in interfaceNames) {
            SSIDInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
            BOOL isNotEmpty = (SSIDInfo.count > 0);
            if (isNotEmpty) {
                break;
            }
        }
        // ssid信息 即wifi名称
        NSString *ssid = [SSIDInfo objectForKey:@"SSID"];
        // bssid信息 即mac地址
        NSString *bssid = [SSIDInfo objectForKey:@"BSSID"];
        NSLog(@"ssid = %@, mac地址 = %@", ssid, bssid);
        if (handler) {
            handler(SSIDInfo);
        }
    }
    
    • 路由器信息
    + (NSString *)routerIp {
        NSString *address = @"error";
        struct ifaddrs *interfaces = NULL;
        struct ifaddrs *temp_addr = NULL;
        int success = 0;
        success = getifaddrs(&interfaces);
        if (success == 0) {
            temp_addr = interfaces;
            while(temp_addr != NULL){
                if(temp_addr->ifa_addr->sa_family == AF_INET) {
                    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                        address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                        NSLog(@"广播地址--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)]);
                        NSLog(@"本机地址--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);
                        NSLog(@"子网掩码地址--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)]);
                        NSLog(@"interface--%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
                    }
                }
                temp_addr = temp_addr->ifa_next;
            }
        }
        
        // Free memory
        freeifaddrs(interfaces);
        
        in_addr_t i = inet_addr([address cStringUsingEncoding:NSUTF8StringEncoding]);
        in_addr_t* x = &i;
        unsigned char *s = getdefaultgateway(x);
        NSString *ip=[NSString stringWithFormat:@"%d.%d.%d.%d",s[0],s[1],s[2],s[3]];
        free(s);
    
        return ip;
    }
    • DNS服务器
    // 获取本机DNS服务器
    + (NSString *)dnsServers {
        res_state res = malloc(sizeof(struct __res_state));
        int result = res_ninit(res);
        NSMutableArray *dnsArray = @[].mutableCopy;
        if ( result == 0 ) {
            for ( int i = 0; i < res->nscount; i++ ) {
                NSString *s = [NSString stringWithUTF8String :  inet_ntoa(res->nsaddr_list[i].sin_addr)];
                [dnsArray addObject:s];
            }
        } else {
            NSLog(@"%@",@" res_init result != 0");
        }
        res_nclose(res);
        return dnsArray.firstObject;
    }
    • 手机的网络IP地址
    + (NSString *)phoneInNetIp {
        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;
    }
    • WiFi设置
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
  • Over

    多说两句:多数时候解决问题需要找思路,一旦确定有解,要实现的就是Code。代码不是最全,网络不少人已贴出来,在此不多写。

以上是关于iOS之WiFi IP相关的主要内容,如果未能解决你的问题,请参考以下文章

iOS搭建IPV6wifi测试网络

iOS开发之APP推送设置WIFI

iOS获取WIFI的IP子网掩码,以及域名转IP

iOS--------获取当前连接的WiFi以及IP地址

ios之应用内跳转系统设置相关界面

54 ESP32Wifi模块之开启AP+STA共存及IP_NAPT模式