通过 C# 验证用户输入的 IP 地址或主机名
在我的 Windows 窗体应用程序的几个字段中,我要求用户提供 IP 地址或主机名。是否有一个好的正则表达式(regex)来验证输入的值?或者我应该考虑其他方法?请注意,我希望用户输入 FQDN 或 IP 地址。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了让您的应用程序面向未来,我建议仅使用
IPAddress.TryParse()
来确定输入是否是 IP 地址。检查“有效”主机名更加困难,也是因为您没有指定主机名是否必须存在。如果确实如此,最简单的方法是使用 Dns.GetHostEntry() 来查看是否产生结果。根据您提供的描述,您无法获得更准确的验证。
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.尝试调用 IPAddress.TryParse ,如果尝试 Dns.GetHostByName 失败
try to call IPAddress.TryParse , if it fails try to Dns.GetHostByName
如果您想验证格式是否有效,可以使用
正则表达式来代替,因为正则表达式可能容易出错。我在预配置应用程序中使用它,用户可以指定将来设置的主机名。为此,
Dns.GetHostEntry
不适合,因为它尝试解析主机名,但由于尚未分配,因此会失败。所以这取决于你的需求。如果用户应该输入实际可以解析的主机名,您可能需要使用
Dns.GetHostEntry()
或IPAddress.TryParse()
。如果您只想进行输入验证,请尝试Uri.CheckHostName
。If you like to validate if the format is valid, you can use
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()
orIPAddress.TryParse()
. If you just want to do input validation, tryUri.CheckHostName
.为什么需要询问 Windows 窗体应用程序的 IP 地址和主机名?如果这些是本地 PC 详细信息,您可以从以下位置获取这些信息:-
1) 要获取主机名,您可以调用 Dns.GetHostName() (请参阅 MSDN 参考)
2) 要获取 IP 地址,您可以通过 < 枚举 IP 地址强>Dns.GetHostByName()(请参阅MSDN 参考)
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)