Check string is ip address in c#

In C#, we can validate a given string is a valid ip address or not by using IPAddress.TryParse method. The below C# function check and returns whether the given string value is valid ip address or not.

private static bool IsIPAddress(string ipAddress)
{
    bool retVal = false;

    try
    {
        IPAddress address;
        retVal = IPAddress.TryParse(ipAddress, out address);
    }
    catch (Exception ex)
    {
    }
    return retVal;
}

We can also check AddressFamily of the given ip address.

IPAddress address;
if (IPAddress.TryParse(ipAddress, out address))
{
    switch (address.AddressFamily)
    {
        case System.Net.Sockets.AddressFamily.InterNetwork:
            // This is IPv4 address
            break;
        case System.Net.Sockets.AddressFamily.InterNetworkV6:
            // This is IPv6 address
            break;
        default:
            break;
    }
}

Advertisement

Leave a Comment