C#

时间:2015-11-09 19:48:02

标签: c# ip-address ipv6

我正在尝试确定硬编码字符串是否是有效的IPv4或IPv6地址。我意识到太晚了,因为有一个IPAddress类,所以我试图继续我不必要的困难方式。我有一个完全正常的findIPv4方法,但是当我尝试复制它并为IPv6方法略微修改它时,它不起作用(因为IPv6使用十六进制并且可以有字符a-f)。我认为问题出在!section.ToLowerInvariant()。包含('d')if语句的一部分,但我不确定。

public string findIPv6(string ipv6)
    {
        // This will split the user inputted string at every instance of a ':'
        var bytes = ipv6.Split(':');

        // If we do not have 8 bytes, it is not an IPv6 therefore return neither
        if (bytes.Length != 8)
        {
            return "Neither";
        }

        // This will check if there is an integer between 1 and 50
        int value;
        if (Int32.TryParse(ipv6, out value) && (value <= 50 && value >= 1))
        {
            return "Neither";
        }

        foreach (var section in bytes)
        {
            // If the length of the parsed int is not equal to the length
            // of the byte string or  0 > int < 9 or abcdef , return false
            int s;
            if (!Int32.TryParse(section, out s) || !s.ToString().Length.Equals(section.Length) || s < 0 || s > 9 || !section.ToLowerInvariant().Contains('a') || !section.ToLowerInvariant().Contains('b') || !section.ToLowerInvariant().Contains('c') || !section.ToLowerInvariant().Contains('d') || !section.ToLowerInvariant().Contains('e') || !section.ToLowerInvariant().Contains('f'))
            {
                return "Neither";
            }

        }

        return "IPv6";
    }

0 个答案:

没有答案