public static void Main()
string ipAddressString = "173.160.21.227";
string subnetMaskCIDR = "/30";
string ipAddressStringCIDR = "173.140.21.21/30";
string networkAddress = GetCorrectCIDR(ipAddressStringCIDR);
if (networkAddress != null)
Console.WriteLine($"IP Address: {ipAddressString}");
Console.WriteLine($"Subnet Mask (CIDR): {subnetMaskCIDR}");
Console.WriteLine($"Network Address CIDR: {networkAddress}");
Console.WriteLine("Invalid IP address format.");
public static string GetCorrectCIDR(string cidr)
var cidrParts = cidr.Split('/');
if (cidrParts.Length == 2)
var networkAddress = GetNetworkAddress(cidrParts[0], int.Parse(cidrParts[1]));
result = $"{networkAddress}/{cidrParts[1]}";
static string GetNetworkAddress(string ipAddressString, int prefixLength)
IPAddress ipAddress = IPAddress.Parse(ipAddressString);
byte[] subnetMaskBytes = ipAddress.GetAddressBytes();
for (int i = prefixLength; i < subnetMaskBytes.Length * 8; i++)
subnetMaskBytes[byteIndex] &= (byte)~(1 << (7 - bitOffset));
IPAddress subnetMask = new IPAddress(subnetMaskBytes);
byte[] ipAddressBytes = ipAddress.GetAddressBytes();
byte[] networkBytes = new byte[ipAddressBytes.Length];
for (int i = 0; i < ipAddressBytes.Length; i++)
networkBytes[i] = (byte)(ipAddressBytes[i] & subnetMaskBytes[i]);
IPAddress networkAddress = new IPAddress(networkBytes);
return networkAddress.ToString();