How to Clear/Flush the DNS Cache in Win32 API's

Viewed 2472

I am looking for a way to programmatically clear/flush the local win32 dns cache (Equivalent of calling "ipconfig /flushdns").

There were ways to do this with a hidden API in winsock.dll but winsock.dll is no longer part of Windows and as such this method will no longer work.

Does anyone know how this should be done now?

1 Answers
  • Checked ipconfig.exe's dependencies using Dependency Walker
  • Found dnsapi.dll among them
  • Checked its exported functions, and found DnsFlushResolverCache
  • Shallowly browsed the web, and found its signature (only found references like this on official site: [MS.Docs]: Windows 8 API Sets), meaning it's not public, so software relying on it, is not robust)
  • Created a small test program

main00.c:

#include <stdio.h>
#include <Windows.h>

typedef BOOL (WINAPI *DnsFlushResolverCacheFuncPtr)();


int main() {
    HMODULE dnsapi = LoadLibrary("dnsapi.dll");
    if (dnsapi == NULL) {
        printf("Failed loading module: %d\n", GetLastError());
        return -1;
    }
    DnsFlushResolverCacheFuncPtr DnsFlushResolverCache = (DnsFlushResolverCacheFuncPtr)GetProcAddress(dnsapi, "DnsFlushResolverCache");
    if (DnsFlushResolverCache == NULL) {
        printf("Failed loading function: %d\n", GetLastError());
        FreeLibrary(dnsapi);
        return -2;
    }
    BOOL result = DnsFlushResolverCache();
    if (result) {
        printf("DnsFlushResolverCache succeeded\n");
    } else {
        printf("DnsFlushResolverCache succeeded: %d\n", GetLastError());
    }
    FreeLibrary(dnsapi);
    return 0;
}

Output:

e:\Work\Dev\StackOverflow\q052007372>"c:\Install\x86\Microsoft\Visual Studio Community\2015\vc\vcvarsall.bat" x64

e:\Work\Dev\StackOverflow\q052007372>dir /b
dnsapi_func_list.txt
main00.c

e:\Work\Dev\StackOverflow\q052007372>cl /nologo main00.c  /link /OUT:main00.exe
main00.c

e:\Work\Dev\StackOverflow\q052007372>dir /b
dnsapi_func_list.txt
main00.c
main00.exe
main00.obj

e:\Work\Dev\StackOverflow\q052007372>main00.exe
DnsFlushResolverCache succeeded

Note: Even if the function call completed successfully, I am not sure how to check whether it did what it's supposed to do (or better: what its name suggests it should do, which seems to be what you need).
Let me know how it works.



Update #0

Thank you for the info @TimJohnson!! I was too in a rush to look at ipconfig /? ([MS.Docs]: ipconfig) output (which I had in another cmd window :d ) and notice the option :) .
It does work (the cache is heavily updated, and I can see differences before and after running the program) !!!

Related