//------------------------------------------------------------------- // timedemo.cpp // // This application will attempt to show how the Time Protocol // described in RFC-868 may be used to obtain the current time // in San Francisco (i.e., Pacific Daylight Time) derived from // Coordinated Universal Time (UTC) reported by a time-server. // // to compile: $ g++ timedemo.cpp -o timedemo // to execute: $ ./timedemo // // NOTE: This program uses the 'stream-oriented' TCP protocol. // // ----------------------- // // EXERCISE: Find and fix the programming errors in this demo. // // ----------------------- // // programmer: ALLAN CRUSE // written on: 18 MAY 2009 //------------------------------------------------------------------- #include // for gethostbyname() #include // for printf(), perror() #include // for exit() #include // for strcpy() #include // for inet_ntoa() #define TIME_PORT 123 char hostname[] = "time-nw.nist.gov"; int main( int argc, char **argv ) { struct hostent *hp = gethostbyname( hostname ); if ( !hp ) { herror( "gethostbyname" ); exit(1); } char hostaddr[ 16 ] = { 0 }; strcpy( hostaddr, inet_ntoa( *(in_addr*)hp->h_addr ) ); printf( "\n Time-server is \'%s\' (%s) \n", hostname, hostaddr ); struct sockaddr_in saddr = { 0 }; socklen_t salen = sizeof( saddr ); saddr.sin_family = AF_INET; saddr.sin_port = TIME_PORT; saddr.sin_addr.s_addr = inet_addr( hostaddr ); int sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); if ( sock < 0 ) { perror( "socket" ); exit(1); } if ( connect( sock, (sockaddr*)&saddr, salen ) < 0 ) { perror( "connect" ); exit(1); } unsigned int since = 0; int rxbytes = recv( sock, &since, sizeof( since ), 0 ); if ( rxbytes < 0 ) { perror( "recv" ); exit(1); } printf( "\n Received %d bytes from server \n", rxbytes ); unsigned int utc = htons( since ); printf( "\n utc = %u seconds \n", utc ); unsigned int secs = utc % 60; unsigned int mins = ( utc / 60 ) % 60; unsigned int hour = ( utc / 3600 ) % 24; printf( "\n Time now is %02u:%02u:%02u (PST) \n", hour, mins, secs ); printf( "\n" ); }