Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
IpCidr.cs
1using System;
2using System.Net;
3
5{
9 public class IpCidr
10 {
11 private readonly IPAddress address;
12 private readonly byte[] binary;
13 private readonly int range;
14
20 public IpCidr(IPAddress Address, int Range)
21 : this(Address, Address.GetAddressBytes(), Range)
22 {
23 }
24
31 private IpCidr(IPAddress Address, byte[] Binary, int Range)
32 {
33 this.address = Address;
34 this.binary = Binary;
35 this.range = Range;
36 }
37
41 public IPAddress Address => this.address;
42
46 public int Range => this.range;
47
54 public static bool TryParse(string s, out IpCidr Parsed)
55 {
56 s = s.Trim();
57
58 int i = s.IndexOf('/');
59 int Range = -1;
60
61 Parsed = null;
62
63 if (i > 0)
64 {
65 if (!int.TryParse(s.Substring(i + 1), out Range) || Range < 0)
66 return false;
67
68 s = s.Substring(0, i);
69 }
70
71 if (!IPAddress.TryParse(s, out IPAddress Address))
72 return false;
73
74 byte[] Bin = Address.GetAddressBytes();
75 int MaxRange = Bin.Length << 3;
76
77 if (Range < 0)
78 Range = MaxRange;
79 else if (Range > MaxRange)
80 return false;
81
82 Parsed = new IpCidr(Address, Bin, Range);
83
84 return true;
85 }
86
92 public bool Matches(IPAddress Address)
93 {
94 if (Address.AddressFamily != this.address.AddressFamily)
95 return false;
96
97 byte[] Bin = Address.GetAddressBytes();
98 int i, c = Math.Min(this.binary.Length, Bin.Length);
99 int Bits = this.range;
100 byte Mask;
101
102 for (i = 0; i < c && Bits > 0; i++, Bits -= 8)
103 {
104 if (Bits >= 8)
105 Mask = 0xff;
106 else
107 Mask = (byte)(0xff << (8 - Bits));
108
109 if (((this.binary[i] ^ Bin[i]) & Mask) != 0)
110 return false;
111 }
112
113 return Bits <= 0;
114 }
115
116 }
117}
IP Address Rangee, expressed using CIDR format.
Definition: IpCidr.cs:10
bool Matches(IPAddress Address)
Checks if an IP Address matches the defined range.
Definition: IpCidr.cs:92
IPAddress Address
Parsed IP Address
Definition: IpCidr.cs:41
IpCidr(IPAddress Address, int Range)
IP Address Rangee, expressed using CIDR format.
Definition: IpCidr.cs:20
static bool TryParse(string s, out IpCidr Parsed)
Tries to parse an IP Range in CIDR format. (An IP Address alone is considered implicitly having a mas...
Definition: IpCidr.cs:54