/// <summary> /// Initialize instance with array of octets of IP Address. /// </summary> /// <param name="ipAddress">Array of octets of IP Address.</param> public NetworkMask(Octet[] ipAddress) { int n = ipAddress[0].Decimal; if (n < 128) Prefix = 8; else if (n < 192) Prefix = 16; else if (n < 224) Prefix = 24; else Prefix = 32; }
/// <summary> /// Converts from string of subnet mask to prefix /// </summary> /// <param name="subnet">A string of subnet mask looks like 255.255.0.0</param> /// <returns></returns> public static int ToPrefix(string subnet) { Octet[] subnetOctet = new Octet[4]; subnetOctet = ToOctet(subnet); int prefix = 0; byte[] temp = { 0, 128, 192, 224, 240, 248, 252, 254, 255 }; foreach (Octet i in subnetOctet) for (int j = 0; j < temp.Length; j++) if (i.Decimal == temp[j]) prefix += j; return prefix; }
/// <summary> /// Determines IPv4 class of an array of octets. /// </summary> /// <param name="ipAddr">An array of octets of IPv4 address.</param> /// <returns></returns> public static IPv4Class ToNetworkClass(Octet[] ipAddr) { int n = ipAddr[0].Decimal; if (n < 128) return IPv4Class.A; else if (n < 192) return IPv4Class.B; else if (n < 224) return IPv4Class.C; else if (n < 240) return IPv4Class.D; else return IPv4Class.E; }
/// <summary> /// Convert prefix number to octets array. /// </summary> /// <param name="prefix">Prefix number is less than 32.</param> /// <returns></returns> public static Octet[] ToOctet(int prefix) { Octet[] subnetOctet = new Octet[4]; byte[] temp = { 0, 128, 192, 224, 240, 248, 252, 254, 255 }; for (int i = 0; i < subnetOctet.Length; i++) { if (prefix > 8) { subnetOctet[i] = new Octet(255); prefix -= 8; } else { subnetOctet[i] = new Octet(temp[prefix]); prefix = 0; } } return subnetOctet; }
/// <summary> /// Initialize IPv4 address /// </summary> /// <param name="addr">An array of octet of IPv4 address.</param> /// <param name="subnetMask">Subnet mask of IPv4 address.</param> /// <param name="ipClass">Class of IPv4 address.</param> public IPv4Address(Octet[] addr, SubnetMask subnetMask, IPv4Class ipClass) { Octet = addr; _mask = new NetworkMask(subnetMask); _class = ipClass; }