Fastest way to get numerical value of the request's IP Address in ASP.NET
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]开发者_JS百科;
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.HttpWorkerRequest
as 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.
精彩评论