验证IP地址的最佳方法是什么? [英] What is the best way of validating an IP Address?

查看:154
本文介绍了验证IP地址的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种验证参数IP地址的方法。作为一个整体发展新手,我想知道是否有更好的方法。

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.

推荐答案

限制 IPAddress.TryParse 方法是验证字符串是否为字符串可以转换为IP地址,因此如果它提供了一个字符串值,如5,它会将其视为0.0.0.5

The limitation with IPAddress.TryParse method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like "5", it consider it as "0.0.0.5".

另一种验证IPv4的方法可能如下:

Another approach to validate an IPv4 could be following :

public bool ValidateIPv4(string ipString)
{
    if (String.IsNullOrWhiteSpace(ipString))
    {
        return false;
    }

    string[] splitValues = ipString.Split('.');
    if (splitValues.Length != 4)
    {
        return false;
    }

    byte tempForParsing;

    return splitValues.All(r => byte.TryParse(r, out tempForParsing));
}

可以测试如下:

List<string> ipAddresses = new List<string>
{
    "2",
    "1.2.3",
    "1.2.3.4",
    "255.256.267.300",
    "127.0.0.1",
};
foreach (var ip in ipAddresses)
{
    Console.WriteLine($"{ip} ==> {ValidateIPv4(ip)}");
}

输出将是:

2 ==> False
1.2.3 ==> False
1.2.3.4 ==> True
255.256.267.300 ==> False
127.0.0.1 ==> True

您还可以使用 IPAddress.TryParse 但它有局限性,可能导致解析不正确。

You can also use IPAddress.TryParse but it has the limitations and could result in incorrect parsing.

System.Net.IPAddress.TryParse方法


请注意,如果TryParse成功解析输入,则返回true,
但这并不一定意味着生成的IP地址
是有效的。 请勿使用此方法验证IP地址。

但这适用于包含至少包含的普通字符串三个点。类似于:

But this would work with normal string containing at least three dots. Something like:

string addrString = "192.168.0.1";
IPAddress address;
if (IPAddress.TryParse(addrString, out address)) {
       //Valid IP, with address containing the IP
} else {
       //Invalid IP
}

使用 IPAddress.TryParse ,您可以查看存在三个点,然后调用 TryParse 喜欢:

With IPAddress.TryParse you can check for existence of three dots and then call TryParse like:

public static bool ValidateIPv4(string ipString)
{
    if (ipString.Count(c => c == '.') != 3) return false;
    IPAddress address;
    return IPAddress.TryParse(ipString, out address);
}

这篇关于验证IP地址的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆