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

狂风中的少年 提交于 2019-12-18 11:49:18

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/5992700/can-i-temporarily-override-dns-resolution-within-a-net-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!