wasSharpNET – Blame information for rev 27
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
5 | office | 1 | /////////////////////////////////////////////////////////////////////////// |
2 | // Copyright (C) Wizardry and Steamworks 2016 - License: GNU GPLv3 // |
||
3 | // Please see: http://www.gnu.org/licenses/gpl.html for legal details, // |
||
4 | // rights of fair usage, the disclaimer and warranty conditions. // |
||
5 | /////////////////////////////////////////////////////////////////////////// |
||
6 | |||
7 | using System; |
||
8 | using System.Net; |
||
9 | |||
10 | namespace wasSharpNET.Network |
||
11 | { |
||
12 | /// <summary> |
||
13 | /// Subnet Mask. |
||
14 | /// </summary> |
||
15 | /// <remarks>https://blogs.msdn.microsoft.com/knom/2008/12/31/ip-address-calculations-with-c-subnetmasks-networks/</remarks> |
||
16 | public static class SubnetMask |
||
17 | { |
||
18 | public static readonly IPAddress ClassA = IPAddress.Parse("255.0.0.0"); |
||
19 | public static readonly IPAddress ClassB = IPAddress.Parse("255.255.0.0"); |
||
20 | public static readonly IPAddress ClassC = IPAddress.Parse("255.255.255.0"); |
||
21 | |||
22 | public static IPAddress CreateByHostBitLength(int hostpartLength) |
||
23 | { |
||
24 | var hostPartLength = hostpartLength; |
||
25 | var netPartLength = 32 - hostPartLength; |
||
26 | |||
27 | if (netPartLength < 2) |
||
28 | throw new ArgumentException("Number of hosts is to large for IPv4"); |
||
29 | |||
30 | var binaryMask = new byte[4]; |
||
31 | |||
32 | for (var i = 0; i < 4; i++) |
||
11 | office | 33 | if (i * 8 + 8 <= netPartLength) |
27 | office | 34 | { |
5 | office | 35 | binaryMask[i] = 255; |
27 | office | 36 | } |
11 | office | 37 | else if (i * 8 > netPartLength) |
27 | office | 38 | { |
5 | office | 39 | binaryMask[i] = 0; |
27 | office | 40 | } |
5 | office | 41 | else |
42 | { |
||
11 | office | 43 | var oneLength = netPartLength - i * 8; |
5 | office | 44 | var binaryDigit = |
45 | string.Empty.PadLeft(oneLength, '1').PadRight(8, '0'); |
||
46 | binaryMask[i] = Convert.ToByte(binaryDigit, 2); |
||
47 | } |
||
48 | return new IPAddress(binaryMask); |
||
49 | } |
||
50 | |||
51 | public static IPAddress CreateByNetBitLength(int netpartLength) |
||
52 | { |
||
53 | var hostPartLength = 32 - netpartLength; |
||
54 | return CreateByHostBitLength(hostPartLength); |
||
55 | } |
||
56 | |||
57 | public static IPAddress CreateByHostNumber(int numberOfHosts) |
||
58 | { |
||
59 | var maxNumber = numberOfHosts + 1; |
||
60 | |||
61 | var b = Convert.ToString(maxNumber, 2); |
||
62 | |||
63 | return CreateByHostBitLength(b.Length); |
||
64 | } |
||
65 | } |
||
27 | office | 66 | } |