For example, given an IP segment: 127.0.0.1 ~ 127.0.0.255, we want to determine whether a given IP address is in this section, you can first convert the IP address to an integer, and then the integer comparison size is very easy.
For example:
127.0.0.1 = 2130706433
127.0.0.255 = 2130706687
Judge:
127.0.1.253 = 2130706941
Whether the integer size is directly compared within this range can be
To convert an IP address into an integer:
Public Static LongIp2long (stringIP) { string[] ipbytes; Doublenum =0; if(!string. IsNullOrEmpty (IP)) {ipbytes= IP. Split ('.'); for(inti = ipbytes.length-1; I >=0; i--) {num+= ((int. Parse (Ipbytes[i])% the) * MATH.POW ( the, (3-i))); } } return(Longnum;}
Determines whether a given IP address is within the specified range:
long
start = IP2Long(
"127.0.0.1"
);
long
end = IP2Long(
"127.0.0.255"
);
long
ipAddress = IP2Long(
"127.0.1.253"
);
bool
inRange = (ipAddress >= start && ipAddress <= end);
if
(inRange){
//IP Address fits within range!
}
method to determine whether an IP address is within a specified range