Sebastian Karlsson
Sebastian Karlsson

Reputation: 745

(Libnm) Specifying password when connecting to wifi from C program

I have found out how to connect to a wifi-network from a C program using the following function:

https://developer.gnome.org/libnm/stable/NMClient.html#nm-client-activate-connection-async

Now, my question is; what if the network requires a password? The function has no such argument.

Upvotes: 1

Views: 698

Answers (1)

Don Quijote
Don Quijote

Reputation: 51

you need generate a NMSettingWirelessSecurity with password to connection. take a look at nmcli root/src/nmcli/devices.c which use libnm

generate NMSettingWirelessSecurity

s_wsec = nm_connection_get_setting_wireless_security(connection);

add setting

nm_connection_add_setting(connection, NM_SETTING(s_wsec));

set password NMSettingWirelessSecurity

if (ap_wpa_flags == NM_802_11_AP_SEC_NONE && ap_rsn_flags == NM_802_11_AP_SEC_NONE) {
    /* WEP */
    nm_setting_wireless_security_set_wep_key(s_wsec, 0, password);
    g_object_set(G_OBJECT(s_wsec),
                    NM_SETTING_WIRELESS_SECURITY_WEP_KEY_TYPE,
                    wep_passphrase ? NM_WEP_KEY_TYPE_PASSPHRASE : NM_WEP_KEY_TYPE_KEY,
                    NULL);
} else if ((ap_wpa_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)
            || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_PSK)
            || (ap_rsn_flags & NM_802_11_AP_SEC_KEY_MGMT_SAE)) {
    /* WPA PSK */
    g_object_set(s_wsec, NM_SETTING_WIRELESS_SECURITY_PSK, password, NULL);
}

activate

nm_client_add_and_activate_connection_async(nmc->client,
                                                    connection,
                                                    info->device,
                                                    info->specific_object,
                                                    NULL,
                                                    add_and_activate_cb,
                                                    info);

Upvotes: 3

Related Questions