dotnet / WatsonWebserver

Watson is the fastest, easiest way to build scalable RESTful web servers and services in C#.
MIT License
411 stars 84 forks source link

Question: how can I determine that the client sent a request to the web server from the same computer where the web server is running? #116

Closed user4000 closed 1 year ago

user4000 commented 1 year ago

Hello dear Joel! I have been using your wonderful web server for many years. Could you help me, how can I determine that the client sent a request to the web server from the same computer where the web server is running? for example I have a request handler method:

async Task MyHandler(HttpContext ctx) { // here I have to determine that the client sent a request to the web server from the same computer where the web server is running }

Note: I always execute Watson Web Server using address * (asterisk)

jchristn commented 1 year ago

Hi Timur! Good to hear from you. I would use HttpContext.Request.Source which includes an IpAddress property. You can use a method like the below to indicate if the request came from localhost.

bool IsLocalRequest(HttpContext ctx)
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            if (ip.ToString().Equals(ctx.Request.Source.IpAddress) return true;
        }
    }
    return false;
}

Obviously this could be optimized in a number of ways: 1) pre-caching the result of Dns.GetHostEntry(Dns.GetHostName()) into a variable and re-using it and 2) using LINQ to test if ctx.Request.Source.IpAddress is within the host.AddressList object.

Hope this helps!