简体   繁体   中英

How to simulate DNS name resolution failure in WebRequest?

Recently discovered that using async socket API in C# actually executes the DNS resolve on the calling thread, so if there is a problem with the resolve it will hang until timeout.
I would like to find a way to simulate DNS resolve problems without touching the running code so the QA can also use it in tests.

Insentive : Many .NET async API's like WebRequest, Image (WinForms, WPF) execute the DNS resolution on the calling thread that can result in hangs of the UI.

Example: (what I would like to be able to simulate)
If DNS fails to resolve the code will never reach (1) but an exception will be thrown from EndGetResponse in (2) after some timeout delay.

class Program
{
    static void Main()
    {
        var request = WebRequest.Create("http://www.google.com");
        request.BeginGetResponse(WebRequestCallback, request);
        // (1)
        Console.ReadLine();
    }
    private static void WebRequestCallback(IAsyncResult ar)
    {
        // (2)
        var response = ((WebRequest) ar.AsyncState).EndGetResponse(ar);
    }
}

Thx Hans, excellent idea.
I will just add the exact steps:

  1. Control panel -> network -> change adapter settings
  2. Double click the connection you use
  3. Properties on the TCP protocol you use
  4. Advanced
  5. DNS tab
  6. Add DNS server IP (*)
  7. Close all network windows
  8. Run: "ipconfig /flushdns"

(*) It must be IP that can be resolved but doesn't return DNS reply (google.com is good) because otherwise the DHCP will return response too fast that the address in unresolvable, and if the server exist it should not return response so the timeout will be reached.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM