我可以在 .NET 应用程序中临时覆盖 DNS 解析吗? [英] Can I temporarily override DNS resolution within a .NET application?
问题描述
我有一些包装器代码,用于运行一组 NUnit 测试,这些测试扫描实时网站以获取某些响应代码.
I have some wrapper code that runs a set of NUnit tests that scan live websites for certain response codes.
我想在不同的服务器上运行这些测试.手动运行时,我可以通过编辑 WindowsSystem32drivers 中的/etc/hosts 文件并将 www.mysite.com 临时设置为 10.0.0.whatever 来完成此操作
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 WindowsSystem32drivers and temporarily setting www.mysite.com to 10.0.0.whatever
有什么办法可以在 .NET 控制台应用程序中执行相同的操作 - 临时覆盖 DNS 记录或以某种方式拦截解析并返回不同的 IP 地址?
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?
这是用于测试网络场中的多个服务器.我有三台实时服务器,所有服务器都认为它们是 www.example.com.因为服务器使用 HTTP 主机标头,所以我不能只针对 server1、server2、server3 运行测试,因为对 http 的 HTTP 请求://server1/ 不会返回与对 http://www.example 的请求相同的内容.com/ 解析为 server1...
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...
推荐答案
过去使用 C++ 我能够挂钩到 WSOCK32.DLL 的 gethostbyname 函数并重新路由 DNS 请求.我使用了 Microsoft Detours 库来做到这一点.
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.
至于 C#,我发现了这个:http://easyhook.codeplex.com/ 也许它会有所帮助你.基本上,您可以连接到 gethostbyname
窗口函数并执行您自己的代码或返回不同的结果(不同的 IP).
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.
我找到了我的旧 C++ 代码,也许它会给你一个提示.
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;
}
找到了新版本的 easyhooks 的另一个链接
Found another link with newer release of easyhooks
这篇关于我可以在 .NET 应用程序中临时覆盖 DNS 解析吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!