Search code examples
c#nunitdnshosts-fileipconfig

Can I temporarily override DNS resolution within a .NET application?


I have some wrapper code that runs a set of NUnit tests that scan live websites for certain response codes.

I'd like to run these tests against a different server. When running manually, I can do this by editing the /etc/hosts file in Windows\System32\drivers and temporarily setting www.mysite.com to 10.0.0.whatever

Is there any way I can do the same within a .NET console application - temporarily override a DNS record or somehow intercept the resolution and return a different IP address?

EDIT: This is for testing multiple servers in a web farm. I have three live servers, all of which THINK they are www.example.com. Because the servers use HTTP host headers, I can't just run a test against server1, then server2, then server3, because an HTTP request to http://server1/ will NOT return the same thing as a request to http://www.example.com/ that's resolved to server1...


Solution

  • In the past with C++ I was able to hook to the WSOCK32.DLL's gethostbyname function and reroute DNS requests. I used the Microsoft Detours library to do that.

    As for C# I found this: http://easyhook.codeplex.com/ maybe it will help you. Basically you can hook to the gethostbyname windows function and execute your own code or return a different result (different IP).

    The other possible solution is to temporarily (and programatically) edit the hosts file when the application starts and ends. From your own code.

    EDIT: I found my old C++ code, maybe it will give you a hint what to do.

    struct hostent FAR * WSAAPI MyGetHostByName(IN const char FAR * name)
    {
        // Call the regular function 
        struct hostent* ret = GetHostByNameFunction(name);
        // Check if it's the hostname you want to reroute
        if ( strcmp(host, (char*)name) == 0 )
        {
            // Edit the IP returned by the regular gethostbyname
            ret->h_addr_list[0] = hostIP;
            ret->h_length = 15;
        }
        // Return the result
        return ret;
    }
    

    EDIT2: Found another link with newer release of easyhooks