-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubnetIpAddress.cs
116 lines (100 loc) · 3.04 KB
/
SubnetIpAddress.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Text.RegularExpressions;
namespace Dusty.Net
{
public class SubnetIpAddress : ComparableIPAddress
{
//Constructors from base class
public SubnetIpAddress(byte[] address) : base(address)
{
init(SubnetMask.GetDefaultValue(this.AddressFamily));
}
public SubnetIpAddress(long newAddress) : base(newAddress)
{
init(SubnetMask.GetDefaultValue(this.AddressFamily));
}
public SubnetIpAddress(byte[] address, long scopeid) : base(address, scopeid)
{
init(SubnetMask.GetDefaultValue(this.AddressFamily));
}
//Extended constructors
public SubnetIpAddress(byte[] address, byte[] subnetMask) : base(address)
{
init(new SubnetMask(subnetMask));
}
public SubnetIpAddress(long newAddress, long subnetMask) : base(newAddress)
{
init(new SubnetMask(subnetMask));
}
public SubnetIpAddress(byte[] address, byte[] subnetMask, long scopeid) : base(address, scopeid)
{
init(new SubnetMask(subnetMask));
}
public SubnetIpAddress(IPAddress ipaddress, SubnetMask subnetMask) : base(ipaddress.GetAddressBytes())
{
init(subnetMask);
}
private void init(SubnetMask mask)
{
this.mask = mask;
byte[] networkBytes = Utils.GetBytes(Utils.GetNetworkBits(this.GetAddressBits(), mask.NetworkPrefixLength));
this.network = new NetworkAddress(
new IPAddress(networkBytes),
mask
);
}
private SubnetMask mask
{
get
{
return mask;
}
set
{
if (value.AddressFamily != this.AddressFamily)
{
throw new ArgumentException("Subnet mask is not of same family as IP address");
}
this.mask = value;
}
}
public SubnetMask subnetMask {
get
{
return mask;
}
}
private NetworkAddress network;
public NetworkAddress networkAddress
{
get
{
return network;
}
}
public string ToCidrString()
{
return string.Format(
"{0}/{1}",
Regex.Replace(ToString(), "%.*$", ""),
subnetMask.NetworkPrefixLength
);
}
public bool IsInSameSubnet(IPAddress comparisonIp)
{
return Utils.IsInSameSubnet(this, comparisonIp);
}
public NetworkAddress GetNetworkAddress()
{
return new NetworkAddress(
new IPAddress(Utils.GetBytes(this.GetNetworkBits())),
this.subnetMask
);
}
}
}