when you say "if one exists" does that mean that from the url 'http://peeron.com/inv' you don't want to get anything? Or do you want to get 'peeron.com'? or maybe '66.216.39.12'?
for the simplest case, you just want to get the ip from a url like 'http://66.216.39.12/inv'. A simple regex to do this would be:
$url = "http://66.216.39.12/inv";
$url =~ m!https?://((?:\d{1,3}\.){3}\d{1,3})!i;
$ip = $1;
of course, this will also match things like "http://999.999.999.999/", but I'm not going to worry about that.
For the more complex case, where you actually want the real ip, given the hostname, I'd use Net::DNS. Shamelessly copied from the Net::DNS manpage
use Net::DNS;
my $url = "http://peeron.com/inv";
$url =~ m!https?://([^/]+)!i;
my $res = Net::DNS::Resolver->new;
my $query = $res->search($1);
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq "A";
print $rr->address, "\n";
}
} else {
print "query failed: ", $res->errorstring, "\n";
}
Again, the usual warnings - this assumes you have a valid URI, and not something that will buffer overflow your DNS server, for example.
update: or look below at rob_au's reply, for the really clean solution.
-- Dan |