-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipValidation.cs
More file actions
96 lines (85 loc) · 2.42 KB
/
ipValidation.cs
File metadata and controls
96 lines (85 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
class Program
{
static void Main()
{
Console.Clear();
// Start of the program
string? ipv4Input;
bool validInput;
Console.WriteLine("Enter an IPv4 address to be validated: ");
do
{
validInput = true;
ipv4Input = Console.ReadLine();
if (ipv4Input == null || ipv4Input == "" || ipv4Input == ".")
{
ipv4Input = "";
Console.WriteLine("Enter a valid string input");
validInput = false;
}
else
{
foreach (char digit in ipv4Input)
{
if (!char.IsDigit(digit) && digit != '.')
{
Console.WriteLine("The input may only contain digits and periods");
validInput = false;
break;
}
}
}
} while (validInput == false);
if (ValidateIPv4(ipv4Input))
{
Console.WriteLine($"{ipv4Input} is a valid IPv4 address");
}
else
{
Console.WriteLine($"{ipv4Input} is NOT a valid IPv4 address");
}
bool ValidateIPv4(string ip)
{
string[] address = ip.Split(".", StringSplitOptions.RemoveEmptyEntries);
if (ValidateLength() && ValidateZeroes() && ValidateRange())
{
return true;
}
else
{
return false;
}
bool ValidateLength()
{
if (address.Length == 4)
return true;
else
return false;
}
bool ValidateZeroes()
{
foreach (string num in address)
{
if (num.Length > 1 && num.StartsWith("0"))
{
return false;
}
}
return true;
}
bool ValidateRange()
{
foreach (string num in address)
{
int value = int.Parse(num);
if (value < 0 || value > 255)
{
return false;
}
}
return true;
}
}
}
}