I want to get the system IP address without using outside applications. Right now my code looks like this:
$ip=`host $hostname`;
$ip =~ s/$hostname has address //;
chomp $ip;
I would prefer to avoid using "host". I found something called "IP::Authority" and another thing called "Net::Address::IPv4::Local" both looked as though they could do what I wanted, however both caused my script to make errors about not being able to locate it (by the way what are those things with the colins called, tools, modules, something else?). Is there some standard pseudo-universal way of getting an IP address with perl?
Thanks for any help,
Michael
Re: Getting the system ip address
perldoc -q hostname tells us:
How do I find out my hostname/domainname/IP address?
The normal way to find your own hostname is to call the `hostname` program.
While sometimes expedient, this has some problems, such as not knowing whether you've got the
canonical name or not. It's one of those tradeoffs of convenience versus portability.
The Sys::Hostname module (part of the standard perl distribution) will give you the hostname
after which you can find out the IP address (assuming you have working DNS)
with a gethostbyname() call.
use Socket;
use Sys::Hostname;
my $host = hostname();
my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
Cheers,
Darren :)
Re^2: Getting the system ip address
Thank you very much, thats working great.
Is there any particular way that you reached looking up hostname in perldoc? Or did you arrive at that conclusion from experience?
Re^3: Getting the system ip address
On a *nix system, I typed "perldoc -q hostname" from the commandline. If you're on Windows (which you don't appear to be), then you can find it all at
perldoc.perl.org.
Apart from the Camel, perldoc is my very best friend - and I'd certainly encourage you to get aquainted with it :)
Re^4: Getting the system ip address
I'll have to look into it some more. As with anything when you are just starting out not only do you not know how anything works, but you don't know how to find it either :) perldoc seems plesantly simular to a *nix man page which will probably help me out a lot as that is what I'm use to for looking things up. Thank you very much for all your help, I have some spring boards to work with now.