开发者

Validate a user-entered IP address or hostname via C#

开发者 https://www.devze.com 2023-01-04 07:01 出处:网络
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

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开发者_JAVA技巧 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.


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


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)


If you like to validate if the format is valid, you can use

bool isValid = Uri.CheckHostName(hostname) == UriHostNameType.Dns;

instead of Regex, wich can be error-prone. I use this in a pre-configuration application, where the user can specify a hostname which will be set in the future. For this purpose, Dns.GetHostEntry is not suiteable because it trys to resolve the hostname, which will fail since it's not assigned yet.

So it depends on your needs. If the user should enter a hostname who actually can be resolved, you may want to use Dns.GetHostEntry() or IPAddress.TryParse(). If you just want to do input validation, try Uri.CheckHostName.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号