简体   繁体   English

ip 号码前导零

[英]Leading Zeros on ip number

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 .我想知道 IP 地址是否有效,但我希望我的方法在 4 IP 组件中的任何一个具有前导零且不是0000时返回 false。

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.我需要的是,如果它的 000,不前导零条件变为真,否则如果 IP 数字包含任何前导零,它变为假。

For example:例如:

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

There are better solutions using regex patterns, but I'm practising LINQ.使用正则表达式模式有更好的解决方案,但我正在练习 LINQ。

Can I do this in one statement using LINQ?我可以使用 LINQ 在一条语句中执行此操作吗?

Here is one way to do it.这是一种方法。 Weird Where clause reflects the weirdness of the requirements. Weird Where 子句反映了需求的怪异。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM