Skip to content

Instantly share code, notes, and snippets.

@Edkorenkov
Last active November 29, 2022 09:50
Show Gist options
  • Save Edkorenkov/136a15a3b881cdfb789ecbdd7685f868 to your computer and use it in GitHub Desktop.
Save Edkorenkov/136a15a3b881cdfb789ecbdd7685f868 to your computer and use it in GitHub Desktop.
Validate IP Addresses in .NET
using System.Net;
using System.Linq;
public static bool IsValidIpAddress(string input)
=> IPAddress.TryParse(input, out var ipAddress) && ipAddress.ToString() == input;
public static bool IsValidIpAddress(string input)
=> input.Split(".") switch
{
{Length: 4} parts => parts.All(x => int.TryParse(x, out var y) && y is >= 0 and <= 255),
_ => false,
};
public static bool IsValidIpAddress(string input)
=> input.Split(".") switch
{
{Length: 4} parts => parts.All(x => byte.TryParse(x, out _)),
_ => false,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment