File Coverage

blib/lib/Armadito/Agent/Tools/Hostname.pm
Criterion Covered Total %
statement 22 37 59.4
branch 1 6 16.6
condition 0 3 0.0
subroutine 8 11 72.7
pod 1 1 100.0
total 32 58 55.1


line stmt bran cond sub pod time code
1             package Armadito::Agent::Tools::Hostname;
2              
3 1     1   1740962 use strict;
  1         4  
  1         45  
4 1     1   5 use warnings;
  1         1  
  1         64  
5 1     1   6 use base 'Exporter';
  1         28  
  1         144  
6              
7 1     1   5 use UNIVERSAL::require();
  1         1  
  1         12  
8 1     1   537 use Encode;
  1         8067  
  1         85  
9 1     1   6 use English qw(-no_match_vars);
  1         1  
  1         24  
10              
11             our @EXPORT_OK = qw(
12             getHostname
13             );
14              
15             BEGIN {
16 1 50   1   220 if ( $OSNAME eq 'MSWin32' ) {
17 1     1   562 no warnings 'redefine'; ## no critic (ProhibitNoWarnings)
  1         1  
  1         51  
18 0           Win32::API->require();
19              
20             # Kernel32.dll is used more or less everywhere.
21             # Without this, Win32::API will release the DLL even
22             # if it's a very bad idea
23 0           *Win32::API::DESTROY = sub { };
24             }
25             }
26              
27             sub getHostname {
28 0     0 1   my (%params) = @_;
29              
30 0 0         my $hostname
31             = $OSNAME eq 'MSWin32'
32             ? _getHostnameWindows()
33             : _getHostnameUnix();
34              
35 0 0         if ( $params{short} ) {
36 0           $hostname =~ s/\..*$//;
37             }
38              
39 0           return $hostname;
40             }
41              
42             sub _getHostnameUnix {
43 0     0     Sys::Hostname->require();
44 0           return Sys::Hostname::hostname();
45             }
46              
47             sub _getHostnameWindows {
48 0     0     my $getComputerName = Win32::API->new( "kernel32", "GetComputerNameExW", [ "I", "P", "P" ], "N" );
49 0           my $buffer = "\x00" x 1024;
50 0           my $n = 1024; #pack ("c4", 160,0,0,0);
51              
52 0           $getComputerName->Call( 3, $buffer, $n );
53              
54             # convert from UTF16 to UTF8
55 0           my $hostname = substr( decode( "UCS-2le", $buffer ), 0, ord $n );
56              
57 0   0       return $hostname || $ENV{COMPUTERNAME};
58             }
59              
60             1;
61             __END__
62              
63             =head1 NAME
64              
65             Armadito::Agent::Tools::Hostname - OS-independent hostname computing
66              
67             =head1 DESCRIPTION
68              
69             This module provides a generic function to retrieve host name
70              
71             =head1 FUNCTIONS
72              
73             =head2 getHostname()
74              
75             Returns the host name.