ms_learn_csharp/027_create_methods/ipv4/Program.cs

62 lines
1.7 KiB
C#
Raw Permalink Normal View History

2024-08-10 21:03:39 -04:00
/*
if ipAddress consists of 4 numbers
and
if each ipAddress number has no leading zeroes
and
if each ipAddress number is in range 0 - 255
then ipAddress is valid
else ipAddress is invalid
*/
string ip_addr_1 = "94.88.1.16";
string ip_addr_2 = "255.0.0.255";
string ip_addr_3 = "555..0.555";
string ip_addr_4 = "255.015.0.255";
string ip_addr_5 = "16.f.0.16";
string[] ip_addrs = {ip_addr_1, ip_addr_2, ip_addr_3, ip_addr_4, ip_addr_5};
bool validate_ip(string ipv4) {
bool valid = false;
bool lenght = false;
bool zeroes = false;
bool range = false;
string[] ip_segs = ipv4.Split('.');
foreach (string segm in ip_segs){
lenght = segm.Length>0 && segm.Length<=3;
if(lenght){
Int16 segment;
valid = Int16.TryParse(segm, out segment);
if(!valid){
Console.Write($"({segm}) is a invalid ipv4 segment! ");
return false;
} else {
if(segm.StartsWith("0") && segm.Length > 1 || segment < 0 || segment > 255){
Console.Write($"({segm}) is a invalid ipv4 range! ");
return false;
} else {
range = true;
zeroes = true;
}
}
} else {
Console.Write($"({segm}) is a invalid ipv4 lenght! ");
return false;
}
}
if(valid && zeroes && lenght && range) {
return true;
} else {
return false;
}
}
foreach (string ip_addr in ip_addrs){
if(validate_ip(ip_addr)){
Console.WriteLine($"{ip_addr} is a valid IP");
} else {
Console.WriteLine($"{ip_addr} is not a valid IP");
}
}