Search code examples
c#.net.net-corereverse-dns

How do you detect Googlebot using reverse DNS lookup in .NET Core?


I tried adding the following one-liner to output the reverse DNS lookup:

@System.Net.Dns.GetHostEntry(Request.HttpContext.Connection.RemoteIpAddress)

But it only returns the GetHostEntry function output.

I only need this oneliner to put in a if-clause which is the recommended method to detect a Googlebot.


Solution

  • Without more context, I am not sure I completely understand. If you wanted to know if the RemoteIpAddress is coming from Google using a "one-liner" you are almost there. Something like this works for me

    Dns.GetHostEntry(IPAddress.Parse("66.249.66.1")).HostName.Contains("googlebot.com");
    

    That IP address is also the known Google Bot IP address. I hope that helped but again I was not sure the exact question you are asking.

    One other thing to take note of is if you sit behind a proxy you will need to add something like the following to make sure the headers are correct.

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders = ForwardedHeaders.All;
        options.ForwardLimit = 2;
        options.KnownNetworks.Clear();
        options.KnownProxies.Clear();
    });