Simple Network Time Protocol Client. This lib feature: Access to SNTP server, and get Epoch (Unix) time.

SimpleNTP.cpp

Committer:
AkinoriHashimoto
Date:
2015-11-27
Revision:
1:b5a2e4532331
Parent:
0:2be905de8e28

File content as of revision 1:b5a2e4532331:

#include "SimpleNTP.h"

SimpleNTP::Result SimpleNTP::setNTPServer(string _server, unsigned short _port)
{
    server= _server;
    port= _port;

    socket.set_blocking(false, 1500);
    if(socket.init() == -1)
        return ERR_SocketInit;

    if(serverNTP.set_address(server.c_str(), port) == -1)
        return ERR_SetNTPAddr;

    return SUCCESS;
}

long SimpleNTP::getNetworkTime()
{
//    long timeEpoch= -1;
    int idx, bytes;
// LeapIndicator:0(0x00), VersionNumber:4(0x100), Mode:3(0x011);
// -> 0b0010 0011 = 0x23
    char req[49];
    for(idx= 0; idx < 48; idx++)
        req[idx]= 0x00;
    req[48]= NULL;
    req[0]= 0x23;
    bytes= socket.sendTo(serverNTP, (char *)req, 48);
    if(bytes == -1)
        return -1;

// NTP response is max 68 Byte (EXPECTED).
    char resSNTP[70];
    bytes= socket.receiveFrom(serverNTP, resSNTP, sizeof(resSNTP));
    if(bytes == -1)
        return -1;

    // RFC2030; Transmit TimeStamp[40-48Byte]:BigEndian 32bit unsigned long (dec), + 32bit under floating-point.
    unsigned long timeNTP= 0;
    for(idx = 0; idx < 4; idx++)
        timeNTP= (timeNTP << 8) | resSNTP[40+ idx];

//  25567day * 24h * 60m * 60s = 2208988800 s. w/o leap seconds(DEFINED).
// Epoch: 1970/01/01~. NTP:1900/01/01~
//    timeEpoch= timeNTP- 2208988800;
    return timeNTP- 2208988800;//timeEpoch;
}

SimpleNTP::Result SimpleNTP::close()
{
    if(socket.close() == -1)
        return ERR_SocketClose;

    return SUCCESS;
}

// EOF