The UNIX Operating System

TOP

UP


Ray Seyfarth

ORCA


Computer Science

COST

USM




A UDP TIME Client


  • The TIME service is for computers

  • returns seconds since 1-1-1900

  • Useful for synchronizing and time-setting

  • TCP and UDP versions return time as an integer

  • Need to use ntohl to convert
    #define UNIXEPOCH       2208988800      /* UNIX epoch, in UCT secs      */
    /* UNIX epoch starts on 1-1-1970 */
    #define MSG             "what time is it?\n"
    
    int main(int argc, char *argv[])
    {
        char *host = "localhost"; /* host to use if none supplied */
        char *service = "time";   /* default service name         */
        time_t now;               /* 32-bit integer to hold time  */ 
        int s, n;                 /* socket descriptor, read count*/
    
        switch (argc) {
        case 1:
            host = "localhost";
            break;
        case 3:
            service = argv[2];
            /* FALL THROUGH */
        case 2:
            host = argv[1];
            break;
        default:
            fprintf(stderr, "usage: UDPtime [host [port]]\n");
            exit(1);
        }
    
        s = connectUDP(host, service);
    
        (void) write(s, MSG, strlen(MSG));
    
        /* Read the time */
    
        n = read(s, (char *)&now, sizeof(now));
        if (n < 0)
            errexit("read failed: %s\n", strerror(errno));
        now = ntohl((u_long)now);   /* put in host byte order       */
        now -= UNIXEPOCH;           /* convert UCT to UNIX epoch    */
        printf("%s", ctime(&now));
        exit(0);
    }
    


University of Southern Mississippi
Ray.Seyfarth@usm.edu
Updated 20:05 Jun 5, 2000