main.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <unistd.h>
  2. #include <arpa/inet.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <netinet/in.h>
  6. #include <netinet/tcp.h>
  7. #include <fcntl.h>
  8. #include <poll.h>
  9. #include <sys/time.h>
  10. #define socketerrno errno
  11. #define SOCKET_EAGAIN_EINPROGRESS EAGAIN
  12. #define SOCKET_EWOULDBLOCK EWOULDBLOCK
  13. #define INVALID_SOCKET -1
  14. #define SOCKET_ERROR -1
  15. typedef int socket_t;
  16. #include "../common/iobuffer.h"
  17. #include "protocol.pb.h"
  18. int main(int, char**){
  19. int _fd = socket(AF_INET, SOCK_DGRAM, 0);
  20. sockaddr_in sin;
  21. sin.sin_family = AF_INET;
  22. sin.sin_port = htons(23816);
  23. sin.sin_addr.s_addr = inet_addr("192.168.3.131");
  24. MessageHead Head;
  25. Head.Command=RemoNet::CS_SyncTime;
  26. Head.Length=0;
  27. CIOBuffer buffer;
  28. Head.Serialize(buffer.Buffer);
  29. buffer.Length=sizeof(MessageHead);
  30. int32_t ret=sendto(_fd,buffer.Buffer,buffer.Length,0,(sockaddr * )&sin,sizeof(sin));
  31. sockaddr_in from;
  32. socklen_t fromlen=sizeof(sockaddr_in);
  33. ret=recvfrom(_fd,buffer.Buffer,CIOBuffer::IO_BUFFER_SIZE,0,(sockaddr *)&from,&fromlen);
  34. if(ret>0)
  35. {
  36. MessageHead Head;
  37. Head.Deserialize(buffer.Buffer);
  38. if(ret<MessageHead::Size()+Head.Length) return -1;
  39. auto ptr=buffer.Buffer+MessageHead::Size();
  40. RemoNet::SyncTime Req;
  41. Req.ParseFromArray(ptr,Head.Length);
  42. {
  43. struct tm _tm;
  44. _tm.tm_sec = Req.tm_sec();
  45. _tm.tm_min = Req.tm_min();
  46. _tm.tm_hour = Req.tm_hour();
  47. _tm.tm_mday = Req.tm_mday();
  48. _tm.tm_mon = Req.tm_mon();
  49. _tm.tm_year = Req.tm_year();
  50. _tm.tm_wday=Req.tm_wday();
  51. _tm.tm_yday=Req.tm_yday();
  52. _tm.tm_isdst=Req.tm_isdst();
  53. auto timep = mktime(&_tm);
  54. struct timeval tv;
  55. tv.tv_sec = timep;
  56. tv.tv_usec = 0;
  57. if(settimeofday (&tv, (struct timezone *) 0) < 0)
  58. {
  59. printf("Set system datatime error %s!/n",strerror(errno ));
  60. }
  61. }
  62. }
  63. }