Hello again.
I always used naive regexps for hostname validation. But recently I've been
trying to build something more robust and more adherent to related RFCs.
Mostly, I've consulted the following RFCs:
From that I understand that:
- Hostnames might be composed by 1 or more labels (separated by dots)
- Each label may have at most 63 characteres
- Regardless of how many labels there are, it may be at most 255
characters long
- Each label may contain a combination of letters, numbers and hyphens
- No label may begin or end with a hyphen
- Hostnames can't be composed only by numbers
If the hostname is qualified (i.e. there are at least 2 labels), then:
- There may be 2 or more labels
- Last label is a TLD
- TLDs must not be 1 character long or composed only by numbers
- A trailing dot may be present
BTW, consulting RFCs sometimes feels like walking a complex maze full of hidden
traps, because there's always some obscure detail you might overlook.
Things get worse if we consider some hostnames in the wild not adherent to these
rules (e.g. some use underscores, which is valid for DNS, but not when used in
hostnames), and also that there exist internationalized domain names.
I've tested my regex, but chances are, there are corner cases I'm not aware of,
so maybe anyone you might help me find such cases.
This is how I'm doing:
my $hname_re = qr/
^ (?=(?&validchar){1,255}$) (?!\d+$)
(?&label)
(?: (?:\.(?&label))* \.(?&tld) \.? )?
$
(?(DEFINE)
(?<validchar>[a-zA-Z0-9.-])
(?<alnum>[a-zA-Z0-9])
(?<alnumdash>[a-z-A-Z0-9])
(?<label>(?> (?&alnum)
(?: (?&alnumdash){,61}
(?&alnum) )? ) )
(?<tld>(?!(\d+|.)\.?$) (?&label) )
)
/x;
Thanks for any suggestions.
return on_success() or die;
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.