tomazos has asked for the wisdom of the Perl Monks concerning the following question:

I want to convert a scalar containing a machine name such as "somemachine.somecompany.com" into a scalar containing it's IP number such as "123.23.42.3" by looking it up via DNS.

The original name could already be an IP number in which case I don't want to change it.

If the lookup fails I want to get an empty string back.

I have been handed some ugly C code to do this, but it occurs to me that someone must have already done this in Perl.

Anyone know of a builtin/module that does this?

Cheers in advance.

Replies are listed 'Best First'.
Re: DNS Lookup
by tachyon (Chancellor) on Mar 12, 2002 at 08:04 UTC
    use Socket; my $server = "perlmonks.org"; $iaddr = inet_aton($server); die "No server '$server'\n" unless $iaddr; $straddr = inet_ntoa($iaddr); print $straddr, "\n"; # going the other way... $iaddr = inet_aton($straddr); $name = gethostbyaddr($iaddr, AF_INET); print $name;

    This will return an empty string in $iaddr if $server can not be looked up. If you specify say 127.0.0.1 as the server name $straddr will contain this.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: DNS Lookup
by jepri (Parson) on Mar 12, 2002 at 09:23 UTC
    tachyon wins with the simplest answer. Keep in mind though that DNS servers can now return multiple IP addresses (for clusters). So if you key hostnames by IP address you will find odd things happening if you repeat the lookup on the same hostname.<P. At least, I think that's how it works.

    ____________________
    Jeremy
    I didn't believe in evil until I dated it.

Re: DNS Lookup
by grep (Monsignor) on Mar 12, 2002 at 04:34 UTC
      If you are going to flip someone off with a RTFM, please make sure you answer the question succinctly. tomazos is really looking for gethostbyname. Net::DNS works, but is massively overpowered for such a simple operation.

      I'm also not suprised he couldn't find it - the perldocs say to read the C manpages, and the C manpages crap on about returning bizarre structures and converting network byte orders without mentioning "Hands you a ip address from a hostname". It's the sort of thing where if you didn't already know, you'd have to ask - which he did.

      ____________________
      Jeremy
      I didn't believe in evil until I dated it.