| 1 | package Net::NTPTime; | ||
| 2 | |||
| 3 | use Socket; | ||
| 4 | use base qw(Exporter); | ||
| 5 | |||
| 6 | our @EXPORT = qw(get_ntp_time get_unix_time); | ||
| 7 | |||
| 8 | our $VERSION = '1.03'; | ||
| 9 | |||
| 10 | sub get_ntp_time | ||
| 11 | { | ||
| 12 | my $hostname = shift(@_) || '0.north-america.pool.ntp.org'; | ||
| 13 | socket(SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('udp')); | ||
| 14 | my $ipaddr = inet_aton($hostname); | ||
| 15 | my $portaddr = sockaddr_in(123, $ipaddr); | ||
| 16 | my $bstr = "\010" . "\0"x47; | ||
| 17 | send(SOCKET, $bstr, 0, $portaddr); | ||
| 18 | $portaddr = recv(SOCKET, $bstr, 1024, 0); | ||
| 19 | my @words = unpack("N12",$bstr); | ||
| 20 | return($words[10]); | ||
| 21 | } | ||
| 22 | |||
| 23 | sub get_unix_time | ||
| 24 | { | ||
| 25 | my $hostname = shift(@_) || '0.north-america.pool.ntp.org'; | ||
| 26 | return(&get_ntp_time($hostname) - 2208988800); | ||
| 27 | } | ||
| 28 | |||
| 29 | =head1 NAME | ||
| 30 | |||
| 31 | Net::NTPTime | ||
| 32 | |||
| 33 | =head1 SYNOPSIS | ||
| 34 | |||
| 35 | use Net::NTPTime; | ||
| 36 | my $unix_time = get_unix_time; | ||
| 37 | my $unix_time = get_unix_time('ntp.server.com'); | ||
| 38 | my $ntp_time = get_ntp_time; | ||
| 39 | my $ntp_time = get_ntp_time('ntp.server.com'); | ||
| 40 | |||
| 41 | =head1 DESCRIPTION | ||
| 42 | |||
| 43 | Retrieve NTP and UNIX timestamp (unsigned integer) from an NTP server. | ||
| 44 | |||
| 45 | Pollutes the namespace with two functions: get_unix_time & get_ntp_time | ||
| 46 | |||
| 47 | =head1 METHODS | ||
| 48 | |||
| 49 | =head2 get_unix_time(OPTIONAL_NTP_SERVER) | ||
| 50 | |||
| 51 | Returns an integer timestamp indicating the number of elapsed seconds since 00:00 01-JAN-1970. | ||
| 52 | You may include a specific NTP server to ping, or a default server will be used. | ||
| 53 | |||
| 54 | =head2 get_ntp_time(OPTIONAL_NTP_SERVER) | ||
| 55 | |||
| 56 | Returns an integer timestamp indicating the number of elapsed seconds since 00:00 01-JAN-1900. | ||
| 57 | You may include a specific NTP server to ping, or a default server will be used. | ||
| 58 | |||
| 59 | =head1 Version History | ||
| 60 | |||
| 61 | 1.00 - Initial Release | ||
| 62 | |||
| 63 | 1.01 - Bug fix (changed "require Socket" to "use Socket") | ||
| 64 | |||
| 65 | 1.02 - Fixed this POD document | ||
| 66 | |||
| 67 | 1.03 - More documentation fixes | ||
| 68 | |||
| 69 | =head1 Author | ||
| 70 | |||
| 71 | Brandon Bourret | ||
| 72 | |||
| 73 | =head1 License | ||
| 74 | |||
| 75 | Permission is granted to use this software under the same terms as Perl itself. | ||
| 76 | |||
| 77 | Refer to the L<Perl Artistic|perlartistic> license for details. | ||
| 78 | |||
| 79 | =head1 Credits | ||
| 80 | |||
| 81 | The real credit goes to Tim Hogard for writing the code to do this. Thanks! | ||
| 82 | |||
| 83 | =cut |