windows win32 c/c++获取系统dns

本文详细描述了一个使用C++编写的函数DnsGetSystemAddr,它通过`GetNetworkParams`从Windows系统中获取DNS服务器列表。通过两次内存分配调用,函数打印出系统的DNS服务器地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <Windows.h>
#include <iphlpapi.h>

#pragma comment(lib, "IPHLPAPI.lib")

int DnsGetSystemAddr()
{
    FIXED_INFO* pFixedInfo;
    ULONG ulOutBufLen;
    DWORD dwRetVal;

    pFixedInfo = (FIXED_INFO*)malloc(sizeof(FIXED_INFO));
    ulOutBufLen = sizeof(FIXED_INFO);

    if (pFixedInfo == NULL)
    {
        printf("Error allocating memory needed to call GetNetworkParams\n");
        return IS_ERROR;
    }

    // Make an initial call to GetNetworkParams to get the necessary size into the ulOutBufLen variable
    if (GetNetworkParams(pFixedInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
    {
        free(pFixedInfo);
        pFixedInfo = (FIXED_INFO*)malloc(ulOutBufLen);
        if (pFixedInfo == NULL)
        {
            printf("Error allocating memory needed to call GetNetworkParams\n");
            return IS_ERROR;
        }
    }

    // Make a second call to GetNetworkParams using the allocated memory
    if (dwRetVal = GetNetworkParams(pFixedInfo, &ulOutBufLen) == NO_ERROR)
    {
        m_VecSystemDns.clear();
        IP_ADDR_STRING* pDnsServer = &pFixedInfo->DnsServerList;
        while (pDnsServer)
        {
            printf("DNS Server: %s\n", pDnsServer->IpAddress.String);
            pDnsServer = pDnsServer->Next;
        }
    }
    else
    {
        printf("GetNetworkParams failed with error: %d\n", dwRetVal);
        return IS_ERROR;
    }

    if (pFixedInfo != NULL)
    {
        free(pFixedInfo);
    }

    return IS_OK;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值