iOS WiFi IP related

  • Questions

    There is a step to get IP in [iOS Realize WIFI Biography]. By the way, here is a
    summary of common content about WIFI and IP.

    1. Device network IP address
    2. WiFi information
    3. Router address
    4. Native DNS server
    5. Phone's network IP address
    6. Enter WiFi settings
  • Code

    • Device network IP address
    +(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 information
    -(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);
        }
    }
    
    • Router information
    +(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 server
    +(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;
    }
    • Phone's network IP address
    +(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 settings
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
  • Over

    To say a few more words: Most of the time, you need to find ideas to solve problems. Once you are sure that there is a solution, what you want to achieve is Code. The code is not the most complete, many people on the Internet have posted it, so I won’t write more here.

Guess you like

Origin blog.51cto.com/15070994/2643242