-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubnetMask.cs
93 lines (79 loc) · 2.51 KB
/
SubnetMask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections;
using System.Linq;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace Dusty.Net
{
public class SubnetMask : ComparableIPAddress
{
public static SubnetMask GetDefaultValue(AddressFamily family)
{
switch (family) {
case AddressFamily.InterNetworkV6:
return new SubnetMask(
new byte[] {
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF
}
);
case AddressFamily.InterNetwork:
return new SubnetMask(
new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }
);
default:
throw new ArgumentException(
"Invalid address family"
);
}
}
//Constructors
public SubnetMask(byte[] address) : base(address)
{
this.length = this.GetNetworkPrefixLength();
}
public SubnetMask(long newAddress) : base(newAddress)
{
this.length = this.GetNetworkPrefixLength();
}
public SubnetMask(byte[] address, long scopeid) : base(address, scopeid)
{
this.length = this.GetNetworkPrefixLength();
}
//Only interesting property over IPaddress is the concept of Network prefix length (e.g. '24' in '192.168.0.1/24')
private int length;
public int NetworkPrefixLength
{
get { return this.length; }
}
public int GetNetworkPrefixLength()
{
string errHostBits = "Subnet mask contains bits in host section";
BitArray bits = this.GetAddressBits();
bool reachedEndOfNetworkBits = false;
int length = 0;
foreach (bool bit in bits)
{
if (bit)
{
if (reachedEndOfNetworkBits)
{
throw new ArgumentException(errHostBits);
}
else
{
length++;
}
}
else
{
reachedEndOfNetworkBits = true;
}
}
return length;
}
}
}