在网络适配器中添加DNS条目

C++ Add DNS entry into network adapter

本文关键字:DNS 条目 添加 网络适配器      更新时间:2023-10-16

我必须在windows的网络适配器设置中以编程方式添加DNS服务器地址。编程语言为c++。

你可以看看IP Helper API

你可以找到如何使用

使用iphelp设置DNS并在CodeProject上注册。

bool RegSetDNS(LPCTSTR lpszAdapterName, LPCTSTR pDNS)
{
    HKEY hKey;
    string strKeyName = "SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\";
    strKeyName += lpszAdapterName;
    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                strKeyName.c_str(),
                0,
                KEY_WRITE,
                &hKey) != ERROR_SUCCESS)
        return false;
    char mszDNS[100];
    strncpy(mszDNS, pDNS, 98);
    int nDNS;
    nDNS = strlen(mszDNS);
    *(mszDNS + nDNS + 1) = 0x00;    // REG_MULTI_SZ need add one more 0
    nDNS += 2;
    RegSetValueEx(hKey, "NameServer", 0, REG_SZ, (unsigned char*)mszDNS, nDNS);
    RegCloseKey(hKey);
    return true;
}