Looking for regex/code for hostname/machine name validation

陌路散爱 提交于 2019-12-10 21:11:30

问题


Looking for hostname validation regex.

Regular expression to match DNS hostname or IP Address?

In that link gentlemen propose a decent regex. I have a few problems/questions with that:

  • On windows computers/networks names like 1abcd are allowed (verified on our local network)
  • In the proposed regex the dot might appear only once. I'd assume that abc.def.gh is a valid hostname as well, isn't it.

Strange, but also couldn't find any .NET class that can validate hostname string (is it the situation?). Any advice will be highly appreciated.

Update: for any class/method proposal - please advice something that will work both in .NET/C# and SilverLight.


回答1:


In the proposed regex the dot might appear only once. I'd assume that abc.def.gh is a valid hostname as well, isn't it.

The dot MAY appear more than once. Test the regular expression here and you will see that it matches.

Relevant fragment of the regular expression (first part is):

([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*

On windows computers/networks names like 1abcd are allowed (verified on our local network)

From wikipedia:

The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits.

I referred to RFC 952. I will try to update the regular expression for hostnames to be compliant with RFC 1123.




回答2:


Is Uri.CheckHostName a method that can help you ? If the hostname is not recognize, the result will be "Unknown".




回答3:


(?i)(?=.{5,20}$)^(([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])\.)*([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])$

Explanation:

(?i) - Ignore case

(?=.{5,20}$) - Limit the string length within 5 to 20 characters.

^(([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])\.)*([a-z\d]|[a-z\d][a-z\d\-]*[a-z\d])$ - Accepts any alphabets and numeric along with hyphen and dot



来源:https://stackoverflow.com/questions/4645126/looking-for-regex-code-for-hostname-machine-name-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!