#!/usr/bin/perl
#
#
# Note: 
#  1. IPv4 version. 
#  2. universal (IPv4 & IPv6) will be based on Net::DNS::Resolver
#  3. Check all active IP addresses except localhost
#      - do reverse lookup and return the name 
#      - return the first IP address if name is not found
#      - return localhost if all interfaces are down

use strict;
use Socket;
#use Data::Dumper;

# PLATFORM-SPECIFIC
my $pattern = $^O =~ /linux/i ? '^\s+inet\saddr:' : '^\s+inet\s';

if ( ! open(IF,'/sbin/ifconfig|')) {
 print "localhost\n";  # almost impossible
 exit 0;
}

my @ips=grep{$_ ne '127.0.0.1'} map{/$pattern(\S+)\s/} grep{/$pattern(\S+)\s/}<IF>;
close IF;

if (! @ips) {
#    print "localhost\n"; localhost does not work correctly
    print "127.0.0.1\n";
    exit 0;
}
foreach my $ip (@ips) {
  my $iaddr = inet_aton($ip);
  my $name  = gethostbyaddr($iaddr, AF_INET);
  if ($name and $name ne 's_'.'master') { # protect S MASTER from substitution
     print "$name\n";     # as soon as first name found print and exit
     exit 0;
  } 
}

#------------ no name is found after this point
print "@ips[0]\n"; # print first IP from the array (array is not empty)
