Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static bool IsInRange(IPAddress ip, string cidr)
- {
- var parts = cidr.Split('/');
- var ipAddr = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
- var cidrAddr = BitConverter.ToInt32(IPAddress.Parse(parts[0]).GetAddressBytes(), 0);
- // Note: When shifting a negative number all the least segnificant bits will
- // be changed to zero e.g: -1 << 1 = 1111 11110 nothing this is signed byte
- 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
- // this is checking if the given addres is in same network as the cidr addresss
- // https://en.wikipedia.org/wiki/Subnetwork (keyword: "bitwise")
- // applying bitwise AND to a ip and mask yield back the network address.
- return ((ipAddr & cidrMask) == (cidrAddr & cidrMask));
- // NOTE: About shiftting negative
- // example cidr mask == 8
- // -1 << (32 - 8)
- // -1 << 24
- // a signed integer when is negative it's represented like:
- // 1st byte/octet | 2nd byte/octet | 3rd byte/octet |4th byte/octet)
- // (1111 1111) (1111 1111) (1111 1111) (1111 1111)
- // most significant byte to least significant
- }
- // note: code found in Vinchuca botnet project
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement