Search code examples
c#.netdnshttpclient.net-4.6.2

How to prevent DNS lookup when fetching by using HttpClient


I am not sure i am doing correctly or not

Would below way prevent DNS lookup when keep-alive is set false?

The host is : tatoeba.org

The url is : http://188.213.24.161/eng/sentences/show/1

Here screenshots

enter image description here

the url is given as above

the host is set as below

enter image description here


Solution

  • I believe that if you specify your host as an ip address (as you did), then .net will skip the dsn look up (regardless of the keep alive or the host header setting).

    If you dig a little bit into HttpClient you will see it basically uses HttpWebRequest for making the requests. https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs

    HttpWebRequest eventually uses a class called ServicePoint which call a Dns.TryInternalResolve.

    Dns.TryInternalResolve doesn't try to resolve IPAddresses.

    For more info refer to: https://referencesource.microsoft.com/#System/net/System/Net/DNS.cs,f8023b9c19212708

    I also tried to verify that by running the following lines and monitor the requests using netmon

    using (HttpClient c = new HttpClient())
    {
        var response = c.GetAsync(url).Result;
    }
    

    I saw that indeed for a url that contains an host name .net issue a dns request while for requests with an ipAddress as an host name there is no dns request.