What is the best way of validating an IP Address?

后端 未结 10 851
时光取名叫无心
时光取名叫无心 2020-12-25 10:08

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.



        
10条回答
  •  遥遥无期
    2020-12-25 10:40

    try with this:

    private bool IsValidIP(String ip)
        {
            try
            {
                if (ip == null || ip.Length == 0)
                {
                    return false;
                }
    
                String[] parts = ip.Split(new[] { "." }, StringSplitOptions.None);
                if (parts.Length != 4)
                {
                    return false;
                }
    
                foreach (String s in parts)
                {
                    int i = Int32.Parse(s);
                    if ((i < 0) || (i > 255))
                    {
                        return false;
                    }
                }
                if (ip.EndsWith("."))
                {
                    return false;
                }
    
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    

提交回复
热议问题