Friday, January 15, 2016

Invalid IP address check


public static bool IsValidIpAddress(IPAddress address)
        {
            string ip = address != null ? address.ToString() : string.Empty;
               
            if (string.IsNullOrEmpty(ip) ||
                ip == "0.0.0.0" ||
                ip == "127.0.0.1" ||
                Regex.IsMatch(ip, @"^10\.") ||
                Regex.IsMatch(ip, @"^192\.168\."))
            {
                return false;
            }

            var matches = Regex.Matches(ip, @"^172\.(\d+)");
            if (matches.Count == 1)
            {
                int range;
                if (matches[0].Success &&
                    matches[0].Groups.Count == 2 &&
                    Int32.TryParse(matches[0].Groups[1].Value, out range))
                {
                    if (range >= 16 && range <= 31)
                    {
                        return false;
                    }
                }
            }

            return true;

        }

No comments:

Post a Comment