Home > Back-end >  Leading Zeros on ip number
Leading Zeros on ip number

Time:09-27

I am trying to know if a ip is valid, but i want my method return false if any of the 4 ip components has a leading zero ,and its not 000 or 0. Trying to do 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; Example:

  • 0 -> true,
  • 000-> true,
  • 01-> false
  • 001-> false
  • 20 ->true

There are better solutions using regex patterns, but im practising linq, My question is can i do in one statement using this linq?

CodePudding user response:

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;
}
  • Related