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条回答
闹够了就滚
2楼-- · 2020-02-17 06:47

If you don't want to parse every integer, but only IPs, just check . for IPv4 and : for IPv6.

        if (input.Contains(".") || input.Contains(":"))
        {
            IPAddress address;
            if (IPAddress.TryParse(input, out address))
            {
                switch (address.AddressFamily)
                {
                    case AddressFamily.InterNetwork:
                        return Ip4Address;
                    case AddressFamily.InterNetworkV6:
                        return Ip6Address;
                }
            }
        }
查看更多
登录 后发表回答