perl 5.000
[p5sagit/p5-mst-13.2.git] / lib / Sys / Hostname.pm
1 # by David Sundstrom   sunds@asictest.sc.ti.com
2 #    Texas Instruments
3
4 package Sys::Hostname;
5
6 use Carp;
7 require Exporter;
8 @ISA = qw(Exporter);
9 @EXPORT = qw(hostname);
10
11 #
12 # Try every conceivable way to get hostname.
13
14
15 sub hostname {
16
17     # method 1 - we already know it
18     return $host if defined $host;
19
20     # method 2 - syscall is preferred since it avoids tainting problems
21     eval {
22         {
23             package main;
24             require "syscall.ph";
25         }
26         $host = "\0" x 65; ## preload scalar
27         syscall(&main::SYS_gethostname, $host, 65) == 0;
28     }
29
30     # method 3 - trusty old hostname command
31     || eval {
32         $host = `(hostname) 2>/dev/null`; # bsdish
33     }
34
35     # method 4 - sysV uname command (may truncate)
36     || eval {
37         $host = `uname -n 2>/dev/null`; ## sysVish
38     }
39
40     # method 5 - Apollo pre-SR10
41     || eval {
42         ($host,$a,$b,$c,$d)=split(/[:\. ]/,`/com/host`,6);
43     }
44
45     # bummer
46     || Carp::croak "Cannot get host name of local machine";  
47
48     # remove garbage 
49     $host =~ tr/\0\r\n//d;
50     $host;
51 }
52
53 1;