What is the best way of validating an IP Address?

2020-02-18 04:44发布

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.

/// <summary>
/// Check IP Address, will accept 0.0.0.0 as a valid IP
/// </summary>
/// <param name="strIP"></param>
/// <returns></returns>
public Boolean CheckIPValid(String strIP)
{
    //  Split string by ".", check that array length is 3
    char chrFullStop = '.';
    string[] arrOctets = strIP.Split(chrFullStop);
    if (arrOctets.Length != 4)
    {
        return false;
    }
    //  Check each substring checking that the int value is less than 255 and that is char[] length is !> 2
    Int16 MAXVALUE = 255;
    Int32 temp; // Parse returns Int32
    foreach (String strOctet in arrOctets)
    {
        if (strOctet.Length > 3)
        {
            return false;
        }

        temp = int.Parse(strOctet);
        if (temp > MAXVALUE)
        {
            return false;
        }
    }
    return true;
}

Its simple (I could do it) but it seems to do the trick.

标签: c# ip
10条回答
beautiful°
2楼-- · 2020-02-18 05:07
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.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-18 05:10

The framework provides the IPAddress class which in turn provides you the Parse and TryParse methods.

// myAddress is a System.Net.IPAddress instance
if (System.Net.IPAddress.TryParse(strIP , out myAddress)) 
    // IP is valid
else
    // IP isn't valid
查看更多
Animai°情兽
4楼-- · 2020-02-18 05:10

The best Regex solution :

^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

C#

Regex.IsMatch(value, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
查看更多
一纸荒年 Trace。
5楼-- · 2020-02-18 05:13

You can process like that it it is either an ipv4 or ipv6:

    public static string CheckIPValid(string strIP)
    {
        //IPAddress result = null;
        //return !String.IsNullOrEmpty(strIP) && IPAddress.TryParse(strIP, out result);
        IPAddress address;
        if (IPAddress.TryParse(strIP, out address))
        {
            switch (address.AddressFamily)
            {
                case System.Net.Sockets.AddressFamily.InterNetwork:
                    // we have IPv4
                    return "ipv4";
                //break;
                case System.Net.Sockets.AddressFamily.InterNetworkV6:
                    // we have IPv6
                    return "ipv6";
                //break;
                default:
                    // umm... yeah... I'm going to need to take your red packet and...
                    return null;
                    //break;
            }
        }
        return null;
    }
查看更多
登录 后发表回答