使用 libnm 和 glib 更改 IP 地址

问题描述

我正在尝试使用 libnm 在 C++ 应用程序中更改我的接口的 IP 地址,但我找不到一个很好的例子。现在我能够获取设备处理程序并请求连接。

int main(int argc,char *argv[])
{
    NMClient *       client;
    GError *         error = NULL;
    const GPtrArray *connections;
    int              i;

    if (!(client = nm_client_new(NULL,&error))) 


    if (!nm_client_get_nm_running(client)) {
        g_message("Error: Can't obtain connections: NetworkManager is not running.");
        return EXIT_FAILURE;
    }

    // Find the device
    NMDevice* device = nm_client_get_device_by_iface (client,"eno1");

    NMDeviceState state = nm_device_get_state (device);
    if(state == NM_DEVICE_STATE_ACTIVATED)
    {
        NMActiveConnection* connection = nm_device_get_active_connection(device);
        NMIPConfig * ipConfig = nm_active_connection_get_ip4_config(connection);

        //what now?
    }
    else
    {
        const GPtrArray* availableConnections = nm_device_get_available_connections(device);

        for (i = 0; i < availableConnections->len; i++)
        {
            //How do I iterate through available connections,and how can I add an ip address and activate it?   
        }
    }

    g_object_unref(client);

    return EXIT_SUCCESS;
}

不清楚我可以用这些连接做什么,我应该如何修改它们(我想设置 dhcp,或者用最少的配置固定 ip 地址),我应该如何激活连接并存储它。 我无法为此找到一个很好的例子。

解决方法

如果您找到要激活的配置文件 (NMRemoteConnection),您可以使用 nm_client_activate_connection_async() 激活它。

请参阅 libnm 文档 here

现在,您会注意到 nm_client_activate_connection_async() 只是异步 API。这意味着,要使用它,您必须迭代 GMainContext 直到回调返回。通常,D-Bus 本质上是异步的,因为您来回发送消息。这意味着,在 has problems 之上的同步 API。

请注意,激活连接回调被调用,设备几乎没有开始激活。您只能获得 NMActiveConnection,它是您进行的激活的句柄。设备尚未完全启动。 “完全起来”的含义取决于您如何解释它。一种常见的解释是设备的状态一直进展到 NM_DEVICE_STATE_ACTIVATED。如果您想等待,您可以订阅信号并进一步迭代 GMainContext,直到激活成功或失败。

另见what nmcli does

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...