From 9c764c4f90ed5b5734e6b6e31222b54a94b448a1 Mon Sep 17 00:00:00 2001 From: Tim Young Date: Tue, 27 Jun 2017 15:37:33 -0500 Subject: [PATCH] IP addresses print CIDR of /? if it is not a real CIDR approved subnet mask. For example, a subnet mask of .250 gives a /?, but .252 gives /30. While this is not real-life (real life does not tell us when we use a foolish subnet), it helps considerably when testing things. --- EduNetworkBuilder/IPAddress.cs | 52 +++++++++++++++++++++------ EduNetworkBuilder/NetworkInterface.cs | 8 ++--- 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/EduNetworkBuilder/IPAddress.cs b/EduNetworkBuilder/IPAddress.cs index 8da1eb2..f9b4146 100644 --- a/EduNetworkBuilder/IPAddress.cs +++ b/EduNetworkBuilder/IPAddress.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using System.Globalization; using System.Xml; using System.Windows.Forms; - +using System.Text.RegularExpressions; namespace EduNetworkBuilder { @@ -140,19 +140,24 @@ namespace EduNetworkBuilder } } else - { - UInt32 tInt = 0; - int cdr; - int.TryParse(mySplitVal[1], out cdr); - for (int loop = 0; loop < 32; loop++) - { - tInt = (tInt << 1); - if (loop < cdr) tInt++; - } - _mask = tInt; + { + _mask = MaskNumFromCIDRString(mySplitVal[1]); } } + static UInt32 MaskNumFromCIDRString(string cidr) + { + UInt32 tInt = 0; + int cdr; + int.TryParse(cidr, out cdr); + for (int loop = 0; loop < 32; loop++) + { + tInt = (tInt << 1); + if (loop < cdr) tInt++; + } + + return tInt; + } public bool Equals(UInt32 IP) { @@ -228,6 +233,31 @@ namespace EduNetworkBuilder PadIt(_ip.ToIpString()), PadIt(_mask.ToIpString()), PadIt(gw)); return tstring; } + + /// + /// Return the CIDR number for this address. This is the number of 1s before the first 0 + /// + /// + public int CIDRNumber() + { + string mask = GetMask.ToBitString(); + mask = Regex.Replace(mask, "0", ""); + return mask.Length; + } + + /// + /// Return true if the subnet mask is really a true CIDR string /8, /16, etc. + /// It is false if the subnet mask creates a mask that does not map to CIDR. For + /// example, 255.255.255.250 is not a real subnet mask. 252 is. + /// + /// True if there are no 1s after the first 0 + public bool ValidCIDR() + { + int cidr = CIDRNumber(); + UInt32 tMask = MaskNumFromCIDRString(cidr.ToString()); + if (tMask == _mask) return true; + return false; + } } public static class IpHelpers diff --git a/EduNetworkBuilder/NetworkInterface.cs b/EduNetworkBuilder/NetworkInterface.cs index d1670fe..b043735 100644 --- a/EduNetworkBuilder/NetworkInterface.cs +++ b/EduNetworkBuilder/NetworkInterface.cs @@ -151,10 +151,10 @@ namespace EduNetworkBuilder } else { - string mask = myIP.GetMask.ToBitString(); - mask = Regex.Replace(mask, "0", ""); - int count = mask.Length; - tstring += "/" + count.ToString(); + int cidr = myIP.CIDRNumber(); + string answer = cidr.ToString(); + if (!myIP.ValidCIDR()) answer = "?"; + tstring += "/" + answer; } return tstring; }