In a couple of fields in my Windows Forms application, I am asking a user to supply either an IP address or a hostname. Is there a good regular expression (regex) to validate the entered value? Or is there another method that I should consider? Please note I would prefer that the user enters a FQDN or an IP address.
In the interest of future-proofing your application, I'd suggest just using IPAddress.TryParse()
to determine if the input is an IP address.
Checking for a 'valid' hostname is more difficult, also because you didn't specify whether the hostname has to exist or not. If it does, the easiest way would be to use Dns.GetHostEntry()
to see if that yields a result. You can't get much more accurate validation based on the description you gave.