home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume34 / synclockd / part01 / getrtime.c next >
C/C++ Source or Header  |  1993-01-10  |  1KB  |  64 lines

  1. /* (C) Silvano Maffeis, maffeis@ifi.unizh.ch
  2.  * University of Zurich, Switzerland 1992
  3.  *
  4.  * getrtime.c: read time from remote host using udp    
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include <sys/time.h>
  9. #include <sys/types.h>
  10. #include <sys/socket.h>
  11. #include <sys/errno.h>
  12. #include <netinet/in.h>
  13.  
  14. extern errno;
  15.  
  16. void sclose(s)
  17.      int s;
  18. {
  19.   int save;
  20.   
  21.   save = errno;
  22.   (void) close(s);
  23.   errno = save;
  24. }
  25.  
  26. getrtime(addrp, timep)
  27.      struct sockaddr_in *addrp;
  28.      struct timeval *timep;
  29. {
  30.   int s;
  31.   int res;
  32.   char thetime[2*sizeof(long)];
  33.   struct timeval *rtime = (struct timeval *)thetime;
  34.   struct sockaddr_in from;
  35.   int fromlen;
  36.  
  37.   s = socket(AF_INET, SOCK_DGRAM, 0);
  38.   if (s < 0) {
  39.     return(-1);
  40.   }
  41.   addrp->sin_family = AF_INET;
  42.   res = sendto(s, (char *)thetime, 2*sizeof(long), 0, 
  43.            (struct sockaddr *)addrp, sizeof(*addrp));
  44.   if (res < 0) {
  45.     sclose(s);
  46.     return(-1);    
  47.   }
  48.   fromlen = sizeof(from);
  49.   res = recvfrom(s, (char *)thetime, 2*sizeof(long), 0, 
  50.          (struct sockaddr *)&from, &fromlen);
  51.   sclose(s);
  52.   if (res < 0) {
  53.     return(-1);    
  54.   }
  55.   if (res != sizeof(thetime)) {
  56.     errno = EIO;
  57.     return(-1);    
  58.   }
  59.   timep->tv_sec  = ntohl(rtime->tv_sec);
  60.   timep->tv_usec = ntohl(rtime->tv_usec);
  61.   return(0);
  62. }
  63.  
  64.