-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSubnetCalculator.cs
145 lines (111 loc) · 3.17 KB
/
SubnetCalculator.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SubnetCalculatorGUI
{
class SubnetCalculator
{
//Decimal for 192.168.0.1
private UInt32 ip = 3232235521;
// Prefix
private UInt16 prefix = 24;
private UInt32 subnetMask;
private UInt32 wildcardMask;
private UInt32 firstIp;
private UInt32 lastIp;
private UInt32 networkID;
private UInt32 broadcast;
private UInt32 hosts;
public SubnetCalculator() { calculate(); }
public string Ip
{
get { return IpToString(ip); }
set {
// Check if string be converted to ip
System.Net.IPAddress newIp;
if (System.Net.IPAddress.TryParse(value, out newIp)){
ip = IpAsUInt32(newIp);
calculate();
};
}
}
public UInt16 Prefix
{
get { return prefix; }
set
{
if (value > 0 && value <= 30)
{
prefix = value;
calculate();
}
}
}
public void calculate()
{
//prefix stuff
subnetMask = UInt32.MaxValue << (32 - prefix);
wildcardMask = ~subnetMask;
//ip range
networkID = ip & subnetMask;
broadcast = networkID | wildcardMask;
//ip range
firstIp = networkID + 1;
lastIp = broadcast - 1;
hosts = wildcardMask -1;
}
private string IpToString(UInt32 ip)
{
byte[] bytes = BitConverter.GetBytes(ip);
// flip little-endian to big-endian(network order)
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
return new System.Net.IPAddress(bytes).ToString();
}
private UInt32 IpAsUInt32(System.Net.IPAddress ipaddr)
{
byte[] bytes = ipaddr.GetAddressBytes();
// flip big-endian(network order) to little-endian
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bytes);
}
return BitConverter.ToUInt32(bytes, 0);
}
public string FirstIp
{
get { return IpToString(firstIp); }
}
public string LastIp
{
get { return IpToString(lastIp); }
}
public string NetworkID
{
get { return IpToString(networkID); }
}
public string BroadCast
{
get { return IpToString(broadcast); }
}
public string WildcardMask
{
get { return IpToString(wildcardMask); }
}
public string SubnetMask
{
get { return IpToString(subnetMask); }
}
public string Hosts
{
get { return hosts.ToString(); }
}
}
//public class SubnetCalculatorString: SubnetCalculator
//{
//}
}