What is the best way of validating an IP Address?

后端 未结 10 878
时光取名叫无心
时光取名叫无心 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:47

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

提交回复
热议问题