문제

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top