简体   繁体   中英

IPv4 and IPv6 address checker

When I am entering the string "192" and it parses the string, it continues to return IPv4 even when it is not a valid IPv4 address. I tried adding an else if (someIP.GetAddressBytes().Length == 1) but it still returns IPv4.

IPAddress someIP = IPAddress.Parse("192");

if (someIP.GetAddressBytes().Length == 4)
{
    Console.WriteLine("IPv4");
}
else if (someIP.GetAddressBytes().Length == 16)
{
    Console.WriteLine("IPv6");
}
else
{
    Console.WriteLine("Neither");
}

You can use the following code to validate IPv6 and IPv4 addresses:

public static bool IsValidIP(string address)
{
    IPAddress ip;
    if (!IPAddress.TryParse(address, out ip)) return false;

    switch (ip.AddressFamily)
    {
        case AddressFamily.InterNetwork:
            if (address.Length > 6 && address.Contains("."))
            {
                string[] s = address.Split('.');
                if (s.Length == 4 && s[0].Length > 0 && s[1].Length > 0 && s[2].Length > 0 && s[3].Length > 0)
                    return true;
            }
            break;
        case AddressFamily.InterNetworkV6:
            if (address.Contains(":") && address.Length > 15)
                return true;
            break;
    }
    return false;
}

According to documentation , IPAddress.AddressFamily will return either InterNetwork for IPv4 or InterNetworkV6 for IPv6 .

The way that MS parses the string you're entering makes it a valid IP address. They've added a kind of shorthand for dealing with parts of an IP and then they fill in the blanks.

If you look into the remarks section on this page you'll see what I'm talking about.

There are many completely valid representations of an IP Address than just 0.0.0.0 format. "192" probably parses to 0.0.0.192, which is why the program isn't crashing AND why it's length is 4.

If you must only accepted dotted notation, use string.Split combined with int.Parse and create an IPAddress instance yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM