문제

What would be the fastest way to get the numerical format (NOT THE STRING FORMAT) of the client?

string format  : 223.255.254.0
numeric format : 3758095872

I can postcompute this by some code like

    static public uint IPAddressToLong(string ipAddress)
    {
        var oIP = IPAddress.Parse(ipAddress);
        var byteIP = oIP.GetAddressBytes();


        var ip = (uint)byteIP[0] << 24;
        ip += (uint)byteIP[1] << 16;
        ip += (uint)byteIP[2] << 8;
        ip += byteIP[3];

        return ip;
    }

based on the Request.UserHostAddress string but I was hoping that IIS or ASP.NET precomputes this and it's somewhere hidden in the HttpContext.

Am I wrong?

도움이 되었습니까?

해결책

HttpContext does not seem to be doing any more magic than what you already see: a string value in HttpRequest.UserHostAddress

Some background info:

HttpContext.Current.Request is of type System.Web.HttpRequest which takes a System.Web.HttpWorkerRequestas parameter when instantiated.

The HttpWorkerRequest is an abstract class instantiated by hosting implementations like, in case of IIS, System.Web.Hosting.IIS7WorkerRequest which then implements the abstract method GetRemoteAddress() of HttpWorkerRequest which is internally used by HttpRequest.UserHostAddress.

IIS7HttpWorkerRequest knows that REMOTE_ADDR is the IIS property it needs to read and, after going through a few more layers of abstraction while passing around the request context, it all finally ends in calling MgdGetServerVariableW(IntPtr pHandler, string pszVarName, out IntPtr ppBuffer, out int pcchBufferSize); in webengine.dll which simply writes a string of length pcchBufferSize into ppBuffer containing the same stuff you get from HttpRequest.UserHostAddress.

Since i doubt that there are other parts in the HttpContext that get fed request-sender related information, i'm assuming you'll have to keep doing your own magic for conversion for which there are plenty of ideas in the link i posted in the comments.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top