I have a range of ip addresses ,and I need to check that my client which accesses my application falls in that range. I we开发者_运维技巧nt thru few articles, and they shift bits after splitting the IP
for instance 127.0.0.1 is splitted after the '. ' and after splitting we get an array of 4 elements, and each of it is shifted
element 1 >> 24;
etc .... and summed up together to check.
May I know why we use the shift operator here ?
The code should probably be something like that (I haven't run it so you might need to fix small issues like small compilation errors or overflow handling):
uint GetIpValue(uint[] values)
{
return (values[0] << 24) +
(values[1] << 16) +
(values[2] << 8) +
(values[3]);
}
This is create a uint
value that is bigger if the left part of the IP is bigger, which is how IP comparison is usally defined.
You can now calculate each such IP Value to see if it's lower or bigger than another IP Value.
Example:
bool IsIpInRange(uint[] ip, uint[] ipStart, uint[] ipEnd)
{
uint ipValue = GetIpValue(ip);
return ipValue >= GetIpValue(ipStart) && ipValue <= GetIpValue(ipEnd);
}
I'm not sure exactly what you're referring to, but I would hazard a guess that you are using a mask?
i.e. If you want to check that your range is 127.XXX.XXX.XXX then your mask would be /8, meaning you're only keeping 8 bits of the 32. You would then need to shift over 24 bits so you can look at the 127.
127.0.0.1 = 0111 1111 . 0000 0000 . 0000 0000 . 0000 0001
127.0.0.1 & 255.0.0.0 = 0111 1111 . 0000 0000 . 0000 0000 . 0000 0000 = 127.0.0.0
127.0.0.1 & 255.0.0.0 >> 24 = 0111 1111 = 127
Each octet of an IP address is 8 bits, so the whole address is 32 bits and fits in an integer. I'm guessing they're converting the string representation of an IP address to an integer by pulling out the four octets and bit shifting them to the four words in an int
Just guessing here but it seems perfectly logical that since IPv4 addresses fits in integer (4 bytes both of them), checking range can be done through normal <
and >
operators. All you do is packing your IPv4 address in to integer (127.0.0.1 -> 0x7F000001) and check if it is in range of two previously packed edges of interval, just as if you are simply checking if 5 is in 1...10 interval.
It is also much easier to finding out if IP address you have belongs to that masked IP address you are checking against. Pack it to integer, shift both of them to the number of bits that are zeroed in mask and just compare them to each other by simple equality operation. (127.0.0.1/8 -> 0x7F000001 >> 8 -> 0x7F0000 == (0x7F000005 >> 8) <- 127.0.0.5)
精彩评论