Simple Network Time Protocol Client. This lib feature: Access to SNTP server, and get Epoch (Unix) time.
Embed:
(wiki syntax)
Show/hide line numbers
SimpleNTP.cpp
00001 #include "SimpleNTP.h" 00002 00003 SimpleNTP::Result SimpleNTP::setNTPServer(string _server, unsigned short _port) 00004 { 00005 server= _server; 00006 port= _port; 00007 00008 socket.set_blocking(false, 1500); 00009 if(socket.init() == -1) 00010 return ERR_SocketInit; 00011 00012 if(serverNTP.set_address(server.c_str(), port) == -1) 00013 return ERR_SetNTPAddr; 00014 00015 return SUCCESS; 00016 } 00017 00018 long SimpleNTP::getNetworkTime() 00019 { 00020 // long timeEpoch= -1; 00021 int idx, bytes; 00022 // LeapIndicator:0(0x00), VersionNumber:4(0x100), Mode:3(0x011); 00023 // -> 0b0010 0011 = 0x23 00024 char req[49]; 00025 for(idx= 0; idx < 48; idx++) 00026 req[idx]= 0x00; 00027 req[48]= NULL; 00028 req[0]= 0x23; 00029 bytes= socket.sendTo(serverNTP, (char *)req, 48); 00030 if(bytes == -1) 00031 return -1; 00032 00033 // NTP response is max 68 Byte (EXPECTED). 00034 char resSNTP[70]; 00035 bytes= socket.receiveFrom(serverNTP, resSNTP, sizeof(resSNTP)); 00036 if(bytes == -1) 00037 return -1; 00038 00039 // RFC2030; Transmit TimeStamp[40-48Byte]:BigEndian 32bit unsigned long (dec), + 32bit under floating-point. 00040 unsigned long timeNTP= 0; 00041 for(idx = 0; idx < 4; idx++) 00042 timeNTP= (timeNTP << 8) | resSNTP[40+ idx]; 00043 00044 // 25567day * 24h * 60m * 60s = 2208988800 s. w/o leap seconds(DEFINED). 00045 // Epoch: 1970/01/01~. NTP:1900/01/01~ 00046 // timeEpoch= timeNTP- 2208988800; 00047 return timeNTP- 2208988800;//timeEpoch; 00048 } 00049 00050 SimpleNTP::Result SimpleNTP::close() 00051 { 00052 if(socket.close() == -1) 00053 return ERR_SocketClose; 00054 00055 return SUCCESS; 00056 } 00057 00058 // EOF
Generated on Fri Jul 15 2022 06:22:07 by 1.7.2