使用libnm调用nm_setting_gsm_get_pin返回NULL的问题求助
解决libnm读取GSM PIN码返回NULL的问题
默认情况下,通过nm_client_get_connections()获取的NMConnection对象不会包含敏感机密数据(比如PIN码),这和nmcli不带--show-secrets无法查看PIN码是同一个逻辑。必须显式调用加载机密的接口,才能读取到PIN。
修复步骤:
- 在找到目标
NMConnection(即你的MobileConnection)后,调用nm_connection_load_secrets()加载机密信息 - 该函数需要传入
GError指针捕获可能的错误(你已用sudo运行,权限层面无问题)
修改后的代码示例:
NMClient *client = nm_client_new(NULL, NULL); const GPtrArray *allConnections = nm_client_get_connections(client); NMConnection *MobileConnection = nullptr; g_ptr_array_foreach((GPtrArray *)allConnections, [](gpointer connection, gpointer user_data) { NMConnection **target = (NMConnection **)user_data; std::string thisId = nm_connection_get_id((NMConnection*)connection); if(thisId == "MOBILE") { *target = (NMConnection*)connection; } }, &MobileConnection); if (MobileConnection) { GError *error = nullptr; // 加载机密信息 if (nm_connection_load_secrets(MobileConnection, NULL, &error)) { NMSettingGsm *GsmSettings = nm_connection_get_setting_gsm(MobileConnection); if(GsmSettings != nullptr) { bool autoConf = nm_setting_gsm_get_auto_config(GsmSettings); std::cout << "Auto APN: " << (autoConf ? "true" : "false") << std::endl; const char *PinCh = nm_setting_gsm_get_pin(GsmSettings); if(PinCh != nullptr) { std::string PinString = PinCh; std::cout << "PIN: " << PinString << std::endl; } else { std::cout << "No PIN found" << std::endl; } } } else { std::cout << "Failed to load secrets: " << error->message << std::endl; g_error_free(error); } } // 记得清理资源,比如g_object_unref(client)等
关键说明:
nm_connection_load_secrets()是同步加载机密的接口,也可以用异步版本nm_connection_load_secrets_async()避免阻塞- 加载机密后,
NMSettingGsm里的PIN字段才会被填充,此时调用nm_setting_gsm_get_pin()就能正常获取到值
内容的提问来源于stack exchange,提问作者Klas-Kenny
相关产品推荐
相关产品推荐

