Reputation: 709
I am trying to know if an IP address is valid, but I want my method to return false if any of the 4 IP components has a leading zero, and is not 000
or 0
.
I've tried to do it in one instruction:
public static bool is_valid_IP(String ip) {
try {
return ip.Split('.')
.ToList()
.Where(x => Convert.ToInt32(x)<=255 && Convert.ToInt32(x)>=0 && notleadingzerocontition)
.Count()==4;
} catch(Exception) {
return false;
}
}
What I need is that not leading zero condition goes true if its 000, but otherwise if the IP number contains any leading zero it goes false.
For example:
0
-> true
000
-> true
01
-> false
001
-> false
20
-> true
There are better solutions using regex patterns, but I'm practising LINQ.
Can I do this in one statement using LINQ?
Upvotes: 0
Views: 400
Reputation: 16761
Here is one way to do it. Weird Where clause reflects the weirdness of the requirements.
public static bool is_valid_IP(String ip)
{
var parts = ip.Split('.');
return parts.Length == 4 && parts
.Select(x => new { StringValue = x, Parsed = int.TryParse(x, out int i), IntValue = i })
.Where(x => x.Parsed && x.IntValue <= 255 && x.IntValue >= 0 &&
(x.StringValue[0] != '0' || x.StringValue == "0" || x.StringValue == "000"))
.Count() == 4;
}
Upvotes: 1