iOS WiFi IP related

Time:2022-11-20
  • Questions

    There is a step to obtain IP in [iOS realizes WIFI transmission]
    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. Local DNS server
    5. The network IP address of the phone
    6. Enter WiFi settings
  • Code

    • Device network IP address
    // Get 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
    /*
     * Get wifi information
     * For iOS12 and above versions to obtain wifi information, you need to set Access WIFI Infomation = ON in Capability
     * Before obtaining iOS13, it is necessary to judge whether to agree to the application of geographic location information in the app
     */
    - (void)wifi:(void(^)(NSDictionary *sender))handler {
        if (@available(iOS 13.0, *)) {
            if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
                // Set location permissions
                [[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 information is the wifi name
        NSString *ssid = [SSIDInfo objectForKey:@"SSID"];
        // The bssid information is the mac address
        NSString *bssid = [SSIDInfo objectForKey:@"BSSID"];
        NSLog(@"ssid = %@, mac address = %@", 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(@"enclosure--%@",[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in*)temp_addr->ifa_cityaddr)->sin_addr)]);
                        NSLog(@"String_Log--%@",[NSString stringWithUTF8String:net_attack(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]);
                        NSLog(@"subnet mask address--%@",[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
    // Get the local 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;
    }
    • The network IP address of the phone
    + (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

    Let me say a few more words: Most of the time, you need to find an idea to solve a problem. Once you have a solution, you need to implement Code. The code is not the most complete, and many people on the Internet have posted it, so I won’t write more here.