I have a method to validate a parameter IP Address. Being new to development as a whole I would like to know if there is a better way of doing this.
The framework provides the IPAddress
class which in turn provides you the Parse
and TryParse
methods.
// myAddress is a System.Net.IPAddress instance
if (System.Net.IPAddress.TryParse(strIP , out myAddress))
// IP is valid
else
// IP isn't valid
The limitation with IPAddress.TryParse method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like "5"
, it consider it as "0.0.0.5"
.
Another approach to validate an IPv4 could be following :
public bool ValidateIPv4(string ipString)
{
if (String.IsNullOrWhiteSpace(ipString))
{
return false;
}
string[] splitValues = ipString.Split('.');
if (splitValues.Length != 4)
{
return false;
}
byte tempForParsing;
return splitValues.All(r => byte.TryParse(r, out tempForParsing));
}
It could be tested like:
List<string> ipAddresses = new List<string>
{
"2",
"1.2.3",
"1.2.3.4",
"255.256.267.300",
"127.0.0.1",
};
foreach (var ip in ipAddresses)
{
Console.WriteLine($"{ip} ==> {ValidateIPv4(ip)}");
}
The output will be:
2 ==> False
1.2.3 ==> False
1.2.3.4 ==> True
255.256.267.300 ==> False
127.0.0.1 ==> True
You can also use IPAddress.TryParse
but it has the limitations and could result in incorrect parsing.
System.Net.IPAddress.TryParse Method
Note that TryParse returns true if it parsed the input successfully, but that this does not necessarily mean that the resulting IP address is a valid one. Do not use this method to validate IP addresses.
But this would work with normal string containing at least three dots. Something like:
string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
//Valid IP, with address containing the IP
} else {
//Invalid IP
}
With IPAddress.TryParse
you can check for existence of three dots and then call TryParse
like:
public static bool ValidateIPv4(string ipString)
{
if (ipString.Count(c => c == '.') != 3) return false;
IPAddress address;
return IPAddress.TryParse(ipString, out address);
}
Without using IPAddress class and validating against byte, which is far better than the Int<256 approach.
public Boolean CheckIPValid(String strIP)
{
// Split string by ".", check that array length is 4
string[] arrOctets = strIP.Split('.');
if (arrOctets.Length != 4)
return false;
//Check each substring checking that parses to byte
byte obyte = 0;
foreach (string strOctet in arrOctets)
if (!byte.TryParse(strOctet, out obyte))
return false;
return true;
}
For validating IP Address, use below package
Packages:-
using System.Net; //To use IPAddress, inbuilt functionality
using System.Net.Sockets; //To access AddressFamily,
using System.Text.RegularExpression; //For Regex.IsMatch()
Method:-
public bool ValidIPAddress(string IP)
{
//Validate IP Address , neither IPV4, or V6
if (IPAddress.TryParse(IP, out var address) == false)
return false;
//check for IPV6
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
if (IP.IndexOf("::") > -1)
return true;
return false;
}
//check for IPV4
else
{
//Ipv4 address shouldn't start with 0 eg..it is invalid 0XX.0XX.0XX.0XX
if (Regex.IsMatch(IP, @"(^0\d|\.0\d)"))
return false;
else if (IP.Count(c => c == '.') != 3)
return false;
else
return true;
}
}
check on below link if needed:-
https://lncharan.blogspot.com/2020/09/validate-ip-address-in-c.html