In a couple of fields in my Windows Form application, I am asking a user to supply either an IP address or a hostname. Is there a good RegEx to take care of this business? I would prefer that the user enter a FQDN or IP. Is there a nice way to test for this?
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.
Why would you need to ask for the IP address and for the hostname for a Windows Form application? If these are the local PC details, you could get these from:-
1) To get the hostname, you can call Dns.GetHostName() (see MSDN reference)
2) To get the IP address, you can enumerate the IP address via Dns.GetHostByName() (see MSDN reference)
try to call IPAddress.TryParse , if it fails try to Dns.GetHostByName