postimg
Dec 2009 17

Setting Your Clock From Google0

Posted In Perl By John Hass

It’s time for another episode of, why the hell would you want to do that, I am your host John Hass.  On Today’s show we are going to teach you how to set the time from Google’s web server.

So the first question is why, my answer is why not.  The web is full of useless things, lets add one more.  Once again using Linux and Perl, you must be root to set the time.

#!/usr/bin/perl
use IO::Socket;

IO::Socket is the only required library for this endeavor.

$host=shift || 'www.google.com';

Google does not have to be where you get your time, so you can call the program with your favorite web host, but I figure you go to them for everything else why not go to them for the time.

my $sock = new IO::Socket::INET (
PeerAddr => $host,
PeerPort => '80',
Proto => 'tcp',
);
die "Could not create connection to $host $!\n" unless $sock;

Create the socket connection to Google, we only support http so I just forced the port to 80.

print $sock "HEAD / HTTP/1.1\r\n\r\n";
$ok = 0;
$loop = 0;
$date = "";

Give Google the Head command to ask for some juicy info.

while() {
chomp($_);
#print $_ . "\n";
if ($ok == 0 && $loop == 1) {
print "Could not get the time\n";
close($sock);
}
if ($ok == 1 && $loop == 1) {
if ($_ =~ /Date:/) {
$date = $_;
close($sock);
}
}
if ($_ =~ /200 OK/) {
$ok=1;
$loop++;
}
}
close($sock);

Parse what your momma gave you, we are looking to make sure the request worked ok and we are making sure that we have a date.

if ($date =~ /GMT/) {
print "Date and time is in GMT\n";
print "$date\n";
$date =~ s/\r//g;
$date =~ s/Date: //g;
`date -s "$date"`;
}

lastly we parse out all the junk that we can’t pass to the Linux date command. then we simply set the date.

Thanks for wasting your time with me.

Now go give that network administrator the finger for not letting you specify your own ntp servers!

Source Files: gettime.zip (3)

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • email
  • LinkedIn
  • MySpace
  • PDF
  • Reddit
  • RSS
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter

Leave a comment

Get Adobe Flash playerPlugin by wpburn.com wordpress themes