What is the best way of validating an IP Address?

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

    using System.Net;
    public static bool CheckIPValid(string strIP)
    {
        IPAddress result = null;
        return
            !String.IsNullOrEmpty(strIP) &&
            IPAddress.TryParse(strIP, out result);
    }
    

    and you're done

    Edit 1

    Added some additional checks to prevent exceptions being thrown (which are costly). PS it won't handle unicode.

    Edit 2

    @StephenMurby IPAddress.TryParse will return true if it successfully parsed the string. If you check the documentation for the method though it will throw an exception in two cases.

    1. The string is null.
    2. The string contains unicode characters.

    Its up to you to decide (design decision) whether you want to throw exceptions or return false. When it comes to parsing I generally prefer to return false rather than exceptions (the assumption being this is input that's not guaranteed to be correct).

    Breaking the return statement down, I am saying,

    1. The string is not null (nor empty which won't parse anyway) AND
    2. The IP address parses correctly.

    Remember C# boolean expressions are lazy evaluated, so the CLR won't attempt to even parse the string if it is null or empty.

    About the missing if, you can do something like,

    if (IP.TryParse(strIP, out result)
    {
        return true;
    }
    

    But all you really doing is saying if something is true, return true. Easier to just return the expression straight away.

提交回复
热议问题