Replies To: Ip range how to?

Re: Ip range how to?

Posted 27 May 2005 - 02:34 PM

One option you have is to convert the address and the range boundaries to 32 bit integers and compare them as you would any other number. For example:

// This will give you a 4 element array consisting of the octets in the IP string
String [] addressOctets = HttpContext.Current.Request.UserHostAddress.Split(".".ToCharArray(), 4);
uint addressValue = 0;
// Shift the first octet over 24 bits so that it's in the highest position
// Thus if addressOctets[0] is 0x8D, addressValue will be 0x8D000000
addressValue = (uint)(Convert.ToUInt32(addressOctets[0]) << 24);
// Shift the second over 16 bits and combine it with the previous result
addressValue = addressValue | (uint)(Convert.ToUInt32(addressOctets[1]) << 16);
// As above
addressValue = addressValue | (uint)(Convert.ToUInt32(addressOctets[2]) << 8);
// Don't need to shift the last octet
addressValue = addressValue | Convert.ToUInt32(addressOctets[3]);
// If you can't hard code your boundaries, repeat the above on them.
// Otherwise, you can just convert them by hand:
if (addressValue >= 0x8DD3A100 && addressValue <= 0x8DD3A1FE)
{
// Address was in the specified range
}