Advertisement
ivandrofly

Check if IP Address belongs to a given CIDR

Sep 19th, 2017
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. private static bool IsInRange(IPAddress ip, string cidr)
  2.         {
  3.             var parts = cidr.Split('/');
  4.  
  5.             var ipAddr = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
  6.             var cidrAddr = BitConverter.ToInt32(IPAddress.Parse(parts[0]).GetAddressBytes(), 0);
  7.             // Note: When shifting a negative number all the least segnificant bits will
  8.             // be changed to zero e.g: -1 << 1 = 1111 11110 nothing this is signed byte
  9.             var cidrMask = IPAddress.HostToNetworkOrder(-1 << (32 - int.Parse(parts[1]))); // this is kinda hack to convert cidr mask to it's real representation e.g: /8 = 1111 1111. 0000 0000 . 0000 0000 . 0000 0000
  10.  
  11.             // this is checking if the given addres is in same network as the cidr addresss
  12.             // https://en.wikipedia.org/wiki/Subnetwork (keyword: "bitwise")
  13.             // applying bitwise AND to a ip and mask yield back the network address.
  14.             return ((ipAddr & cidrMask) == (cidrAddr & cidrMask));
  15.  
  16.             // NOTE: About shiftting negative
  17.             // example cidr mask == 8
  18.             // -1 << (32 - 8)
  19.             // -1 << 24
  20.             // a signed integer when is negative it's represented like:
  21.             // 1st byte/octet | 2nd byte/octet | 3rd byte/octet |4th byte/octet)
  22.             // (1111 1111) (1111 1111) (1111 1111) (1111 1111)
  23.             // most significant byte to least significant
  24.         }
  25. // note: code found in Vinchuca botnet project
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement