//------------------------------------------------------------------- // utcdemo.cpp // // This example shows how we can obtain the current time from // an official U.S. government time-server, based on RFC-868, // and then show the time-of-day using Pacific Daylight Time. // In this program we will employ the UDP transport-protocol. // // compile using: $ g++ utcdemo.cpp -o utcdemo // execute using: $ ./utcdemo // // programmer: ALLAN CRUSE // written on: 12 APR 2009 //------------------------------------------------------------------- #include // for gethostbyname() #include // for printf(), perror() #include // for exit() #include // for strcpy() #include // for inet_ntoa() #define TIME_PORT 37 char servername[] = "time-nw.nist.gov"; int main( int argc, char **argv ) { struct hostent *pp = gethostbyname( servername ); if ( !pp ) { herror( "gethostbyname" ); exit(1); } char peeraddr[ 16 ] = { 0 }; strcpy( peeraddr, inet_ntoa( *(in_addr*)pp->h_addr ) ); printf( "\nTime-server is \'%s\' (%s) \n", servername, peeraddr ); struct sockaddr_in saddr = { 0 }; socklen_t salen = sizeof( saddr ); saddr.sin_family = AF_INET; saddr.sin_port = htons( TIME_PORT ); saddr.sin_addr.s_addr = inet_addr( peeraddr ); int sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if ( sock < 0 ) { perror( "socket" ); exit(1); } int tx = sendto( sock, "", 0, 0, (sockaddr*)&saddr, salen ); if ( tx < 0 ) { perror( "sendto" ); exit(1); } unsigned int since = 0; int rx = recvfrom( sock, &since, 4, 0, (sockaddr*)&saddr, &salen ); if ( rx < 0 ) { perror( "recvfrom" ); exit(1); } unsigned int seconds_since_1900 = htonl( since ); // display the Coordinated Universal Time in hh:mm:ss format unsigned int ss = seconds_since_1900 % 60; unsigned int mm = ( seconds_since_1900 / 60 ) % 60; unsigned int hh = ( seconds_since_1900 / 3600 ) % 24; printf( "\nseconds_since_1900: %u \n", seconds_since_1900 ); printf( "\nTime now is %02d:%02d:%02d (GMT) \n", hh, mm, ss ); // display the current Pacific Daylight Time in hh:mm:ss format seconds_since_1900 -= (7 * 3600); ss = seconds_since_1900 % 60; mm = ( seconds_since_1900 / 60 ) % 60; hh = ( seconds_since_1900 / 3600 ) % 24; printf( "\nTime now is %02d:%02d:%02d (PDT) \n", hh, mm, ss ); printf( "\n" ); }