1830938 Members
1865 Online
110017 Solutions
New Discussion

find IP address of host

 
Pat Peter
Occasional Advisor

find IP address of host

Hi,

I need to write a PERL script which returns the IP address of the host.

Can anyone please help.

Thanks,
Pat
4 REPLIES 4
Devesh Pant_1
Esteemed Contributor

Re: find IP address of host

Pat,
assuming you are on a machine with fully qualified domain name,
this will work

#!/usr/bin/perl -wT
use IO::Socket;
$hostname="hostname.yourdomain.com"; #change this to your hostname
my($addr)=inet_ntoa((gethostbyname($hostname))[4]);
print "$addr\n";

there could be other variations that will give you servers behind the routers etc.

thanks
DP
Muthukumar_5
Honored Contributor

Re: find IP address of host

There is an example available in perldoc as,

# perldoc -q hostname

use Sys::Hostname;
my $host = hostname();
my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
print "Hostname = $host" . "\tIP-Address = $addr" . "\n";

You can easily get from shell as,

# getip

hth.
Easy to suggest when don't know about the problem!
Ralph Grothe
Honored Contributor

Re: find IP address of host

I assume "IP address of the host" refers to the host's own IP address that runs the Perl script.

If you want to avoid the import of Socket (just to get inet_ntoa() and the likes)
it requires just two statements, like

chomp($this_node=qx(/usr/bin/uname -n));
$this_ip = join '.', unpack('C4',((gethostbyname $this_node)[-1])[0]);

If you're unhappy with external calls (e.g. taint mode) you could as well get the node name from the POSIX module (at the cost of import)

e.g.

use POSIX 'uname';
($this_node) = (uname)[1];
Madness, thy name is system administration
Ganesha Sridhara
Honored Contributor

Re: find IP address of host

Hello Pat,

Please check this URL:
http://www.perl.com/pub/a/2002/11/20/dns.html
http://home.xnet.com/~efflandt/ip2host.html

The above URL will give good idea about IP 2 host conversion.

Regards
Ganesha Sridhara