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:

If the hostname is qualified (i.e. there are at least 2 labels), then:

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;


In reply to Regex for hostname validation by hrcerq

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.