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
4namespace Waher.Runtime.IO
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(string Endpoint)
93 {
94 if (IPAddress.TryParse(Endpoint.RemovePortNumber(), out IPAddress Address))
95 return this.Matches(Address);
96 else
97 return false;
98 }
99
105 public bool Matches(IPAddress Address)
106 {
107 if (Address.AddressFamily != this.address.AddressFamily)
108 return false;
109
110 byte[] Bin = Address.GetAddressBytes();
111 int i, c = Math.Min(this.binary.Length, Bin.Length);
112 int Bits = this.range;
113 byte Mask;
114
115 for (i = 0; i < c && Bits > 0; i++, Bits -= 8)
116 {
117 if (Bits >= 8)
118 Mask = 0xff;
119 else
120 Mask = (byte)(0xff << (8 - Bits));
121
122 if (((this.binary[i] ^ Bin[i]) & Mask) != 0)
123 return false;
124 }
125
126 return Bits <= 0;
127 }
128
129 }
130}
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:105
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
IpCidr(IPAddress Address, int Range)
IP Address Rangee, expressed using CIDR format.
Definition: IpCidr.cs:20
bool Matches(string Endpoint)
Checks if an IP Address matches the defined range.
Definition: IpCidr.cs:92
IPAddress Address
Parsed IP Address
Definition: IpCidr.cs:41