0

I want to create extension methods which is check sended IP address

Specify at least one IP address from which requests will be made. All requests from other IP addresses are denied. Access can be granted to:

  • A single IP address (e.g. 192.168.0.2)

  • Multiple IP addresses, separated by space (e.g. 192.168.0.2 10.0.0.2)

  • A subnet in CIDR notation (e.g. 192.168.0.0/24)

Enter a list of IPs or at least one IP address (or an IP range) in the text fields in the corresponding sections.

below code which is use but it's not working

public static bool IsIpAddressAllowed(this string clientAddress, string allowedIpRange)
    {
        return IsInRange(clientAddress, allowedIpRange, allowedIpRange); ;
    }




 public static bool IsInRange(string startIpAddr, string endIpAddr, string address)
    {
        long ipStart = BitConverter.ToInt32(IPAddress.Parse(startIpAddr).GetAddressBytes().Reverse().ToArray(), 0);

        long ipEnd = BitConverter.ToInt32(IPAddress.Parse(endIpAddr).GetAddressBytes().Reverse().ToArray(), 0);

        long ip = BitConverter.ToInt32(IPAddress.Parse(address).GetAddressBytes().Reverse().ToArray(), 0);

        return ip >= ipStart && ip <= ipEnd; //edited
    }
Nayeem Mansoori
  • 821
  • 1
  • 15
  • 41
  • Wouldn't be using configuration in your web.config be easier and more flexible than coding this? Maybe check [Is it possible to configure a location in Web.config to only allow local connections](http://stackoverflow.com/q/2337842/205233) and related posts. If your environment allows, you could also consider blocking by firewall rule instead of letting unwanted traffic busy your site. – Filburt Mar 03 '17 at 08:51
  • but i want methods for that. – Nayeem Mansoori Mar 03 '17 at 08:55
  • Why do you put the `allowedIpRange` as second argument `endIpAddr` into your function? Even if this function works as expected, wouldn't it always return `true` with this call? Or is this just for debugging? EDIT: It seems to me, that in this piece of example code, ALL arguments are mixed up. – Lukas Körfer Mar 03 '17 at 09:13
  • I tested your code, the Method `IsInRange` works for me,I don't know about the "subnet in CIDR notation" but this doesn't seem to be very useful here. – thmshd Mar 03 '17 at 09:14

0 Answers0