Given a string, I'd like to check syntactically whether it can be valid domain name or IP. I've found this post by merlyn in 2000:
Test the syntactic validity of a domain name, it seems to be a little too strict, as pointed by others (e.g, misses 411.com). Is there a more "correct" solution, both in terms of speed and what it does. Currently I'm using the following code, which also includes some test cases, are there other cases?
use strict;
use Test::More 'no_plan';
my @good=("www.foo.com","www.411.com","123.34.3.5","web.foo.info",
"www.foo.co.uk","aaaa-4-bbbb.cCc.COM");
my @bad = ("foo.23.4.2","foo","23","234.12.4.5.4","2345.23.4.43");
ok(is_valid($_)) foreach @good;
ok(!is_valid($_)) foreach @bad;
sub is_valid{
my $name = shift;
my $name = lc $name;
return ($name
&& $name =~ /^[-\.\w]+\.\w+$/ #at least two levels
&& ($name !~ /\.\d+$/ || $name =~ /^\d{1,3}\.\d{1,3}\.\d{1
+,3}\.\d{1,3}$/) #if last part is digit, better be ip
);
}
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.