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

1

19

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...

Parceling answered 13/5, 2011 at 13:36 Comment(3)
I think it would be easier not to bother with the DNS. Instead, set the URL of the target to be read from the App.config file. Then you would switch which config file is read depending on what environment you are in - which Visual Studio can manage for you.Curtsey
Jeff - see edit; I need to scan different SERVERS but cannot use different hostnames to talk to them...Parceling
Ah, yes. I suppose that would make things difficult. I suspected from your rep and gold medals that there was something else going on here :)Curtsey
A
7

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

Amphictyony answered 13/5, 2011 at 13:47 Comment(1)
In other words: no, you can't - not within .NET.Overarm

© 2022 - 2024 — McMap. All rights reserved.