How to determine if a string is a valid IPv4 or IP

2020-02-17 06:19发布

I know regex is dangerous for validating IP addresses because of the different forms an IP address can take.

I've seen similar questions for C and C++, and those were resolved with a function that doesn't exist in C# inet_ntop()

The .NET solutions I've found only handle the standard "ddd.ddd.ddd.ddd" form. Any suggestions?

7条回答
smile是对你的礼貌
2楼-- · 2020-02-17 06:25

You can use this to try and parse it:

 IPAddress.TryParse

Then check AddressFamily which

Returns System.Net.Sockets.AddressFamily.InterNetwork for IPv4 or System.Net.Sockets.AddressFamily.InterNetworkV6 for IPv6.

EDIT: some sample code. change as desired:

    string input = "your IP address goes here";

    IPAddress address;
    if (IPAddress.TryParse(input, out address))
    {
        switch (address.AddressFamily)
        {
            case System.Net.Sockets.AddressFamily.InterNetwork:
                // we have IPv4
                break;
            case System.Net.Sockets.AddressFamily.InterNetworkV6:
                // we have IPv6
                break;
            default:
                // umm... yeah... I'm going to need to take your red packet and...
                break;
        }
    }
查看更多
叼着烟拽天下
3楼-- · 2020-02-17 06:29

You may use the IPAddress.GetAddressBytes().Length property

        IPAddress someIP;

        if (someIP.GetAddressBytes().Length == 4)
        {
            // IPV4
        }
        else (someIP.GetAddressBytes().Length == 16)
        {
            // IPV6
        }
        else
        {
            // Unknown
        }

I guess should work

查看更多
贼婆χ
4楼-- · 2020-02-17 06:32

Just a warning about using System.Net.IpAddress.TryParse():

If you pass it an string containing an integer (e.g. "3") the TryParse function will convert it to "0.0.0.3" and, therefore, a valid InterNetworkV4 address. So, at the very least, the reformatted "0.0.0.3" should be returned to the user application so the user knows how their input was interpreted.

查看更多
够拽才男人
5楼-- · 2020-02-17 06:36

You could check out System.Uri.CheckHostName( value ) that returns Unknown , Dns, IPv4, IPv6.

if( Uri.CheckHostName( value ) != UriHostNameType.Unknown)
    //then 'value' is a valid IP address or hostname
查看更多
放我归山
6楼-- · 2020-02-17 06:38
string myIpString = "192.168.2.1";
System.Net.IPAddress ipAddress = null;

bool isValidIp = System.Net.IPAddress.TryParse(myIpString, out ipAddress);

If isValidIp is true, you can check ipAddress.AddressFamily to determine if it's IPv4 or IPv6. It's AddressFamily.InterNetwork for IPv4 and AddressFamily.InterNetworkV6 for IPv6.

查看更多
Summer. ? 凉城
7楼-- · 2020-02-17 06:43

A combination of tests applied to a string or IPAddress, works for me..

        /// <summary>
    /// Test string for valid ip address format
    /// </summary>
    /// 
    /// <param name="Address">The ip address string</param>
    /// 
    /// <returns>Returns true if address is a valid format</returns>
    public static bool IsValidIP(IPAddress Ip)
    {
        byte[] addBytes = Ip.GetAddressBytes();

        switch (Ip.AddressFamily)
        {
            case AddressFamily.InterNetwork:
                if (addBytes.Length == 4)
                    return true;
                break;
            case AddressFamily.InterNetworkV6:
                if (addBytes.Length == 16)
                    return true;
                break;
            default:
                break;
        }

        return false;
    }

    /// <summary>
    /// Test string for valid ip address format
    /// </summary>
    /// 
    /// <param name="Address">The ip address string</param>
    /// 
    /// <returns>Returns true if address is a valid format</returns>
    public static bool IsValidIP(string Address)
    {
        IPAddress ip;
        if (IPAddress.TryParse(Address, out ip))
        {
            switch (ip.AddressFamily)
            {
                case System.Net.Sockets.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 System.Net.Sockets.AddressFamily.InterNetworkV6:
                    if (Address.Contains(":") && Address.Length > 15)
                        return true;
                    break;
                default:
                    break;
            }
        }

        return false;
    }
查看更多
登录 后发表回答