美文网首页
iOS12获取网关地址

iOS12获取网关地址

作者: 今年27 | 来源:发表于2024-01-12 09:42 被阅读0次

    要在有网络的情况下获取,无网络通常无法获取网关ip
    nw_path_monitor_t path_monitor = nw_path_monitor_create();

    nw_path_monitor_set_update_handler(path_monitor, ^(nw_path_t path) {
    if (!nw_path_is_expensive(path) && nw_path_status(path) == nw_path_status_satisfied) {
    nw_path_enumerate_gateways(path, ^bool(nw_endpoint_t gateway) {
    const struct sockaddr *address = nw_endpoint_get_address(gateway);
    if (address->sa_family == AF_INET) { // IPv4
    struct sockaddr_in *ipv4Address = (struct sockaddr_in *)address;
    char gatewayAddressBuffer[INET_ADDRSTRLEN];
    const char *gatewayAddressString = inet_ntop(AF_INET, &(ipv4Address->sin_addr), gatewayAddressBuffer, INET_ADDRSTRLEN);
    if (gatewayAddressString != NULL) {
    NSString *gatewayAddress = [NSString stringWithUTF8String:gatewayAddressString];
    NSLog(@"Gateway Address: %@", gatewayAddress);
    }
    } else if (address->sa_family == AF_INET6) { // IPv6
    struct sockaddr_in6 *ipv6Address = (struct sockaddr_in6 *)address;
    char gatewayAddressBuffer[INET6_ADDRSTRLEN];
    const char *gatewayAddressString = inet_ntop(AF_INET6, &(ipv6Address->sin6_addr), gatewayAddressBuffer, INET6_ADDRSTRLEN);
    if (gatewayAddressString != NULL) {
    NSString *gatewayAddress = [NSString stringWithUTF8String:gatewayAddressString];
    NSLog(@"Gateway Address: %@", gatewayAddress);
    }
    }

            return NO;
        });
    } else {
        NSLog(@"No active network connection.");
    }
    

    });

    nw_path_monitor_set_queue(path_monitor, dispatch_get_main_queue());
    nw_path_monitor_start(path_monitor);

    相关文章

      网友评论

          本文标题:iOS12获取网关地址

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