views:

37

answers:

3

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?

+1  A: 

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.

ErikHeemskerk
Would Dns.GetHostEntry() be useful if the user typed in a host and then clicked on a button to validate the host entry...like the Check Names button on Active Directory related fields?
ThaKidd
Certainly, I've seen this done in multiple tools, the first that springs to mind is IIS SMTP Server Config (when setting the server's FQDN).
ErikHeemskerk
Excellent, that makes perfect sense. Let me give it a try and will be back!
ThaKidd
+1  A: 

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)

Syd
The data would not be used to test things out on the local system. It would be used to determine whether a SSH server exists and also whether the data a user enters is real (as in blahblahblah == wrong, 66.234.34.23 == correct). This question is dealing completely with remote hosts.
ThaKidd
@ThaKidd, thank you for the clarification. On the note, I think you can still use Dns.GetHostByName(hostname) to verify if the hostname is valid. Ditto for the the IP address which you can use Dns.GetHostByAddress() to check the address.
Syd
Dns.GetHostByName and Dns.GetHostByAddress have both been marked obsolete.
ErikHeemskerk
+1  A: 

try to call IPAddress.TryParse , if it fails try to Dns.GetHostByName

Andrey