Share via


c#: How to check a input IP fall in a specific IP range

An IP address can be represented by different notations. The most common way to represent an IP address is XXX.XXX.XXX.XXX. 

To convert an IP address to integer, break it into four octets. For example, the ip address 192.168.52.255 can be broken into

First Octet: 192
Second Octet: 168
Third Octet: 52
Fourth Octet: 255

To calculate the decimal address from a dotted string, perform the following calculation.

(first octet * 256³) + (second octet * 256²) + (third octet * 256) + (fourth octet)
= (first octet * 16777216) + (second octet * 65536) + (third octet * 256) + (fourth octet)
= (192 * 16777216) + (168 * 65536) + (52 * 256) + (255)
= 3232249087
public bool  IsInRange(string  startIp, string  endIp, string  ipAddress)
       {
           string[] start = startIp.Split('.');
           string[] end = endIp.Split('.');
           string[] ipArray = ipAddress.Split('.');
 
           Int64 resultStart = (Convert.ToInt64(start[0]) * 16777216) + (Convert.ToInt64(start[1]) * 65536) + (Convert.ToInt64(start[2]) * 256) + (Convert.ToInt64(start[3]));
           Int64 resultEnd = (Convert.ToInt64(end[0]) * 16777216) + (Convert.ToInt64(end[1]) * 65536) + (Convert.ToInt64(end[2]) * 256) + (Convert.ToInt64(end[3]));
           Int64 ip = (Convert.ToInt64(ipArray[0]) * 16777216) + (Convert.ToInt64(ipArray[1]) * 65536) + (Convert.ToInt64(ipArray[2]) * 256) + (Convert.ToInt64(ipArray[3]));
 
 
           return ip >= resultStart && ip <= resultEnd; //edited
       }