Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top