How to determine if a string is a valid IPv4 or IPv6 address in C#?

前端 未结 7 1270
逝去的感伤
逝去的感伤 2020-12-23 18:48

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 we

7条回答
  •  梦毁少年i
    2020-12-23 19:17

    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;
            }
        }
    

提交回复
热议问题