NTP Client library



  • Can someone suggest me a cross platform (Linux - Windows) library to have the ntp time from a server?
    Regards.


  • Moderators



  • I have bring up this synchronized function that can be used inside a thread.

    // https://github.com/edma2/ntp/blob/master/rfc.txt
    bool GetNTPDateTime(QDateTime &DateTime, QString Server, int Socket) {
        bool Result= false;
        QHostInfo HostInfo= QHostInfo::fromName(Server);
        if (HostInfo.addresses().length()> 0) {
            QUdpSocket *UdpSocket= new QUdpSocket(); {
                UdpSocket->connectToHost(QHostAddress(HostInfo.addresses().at(0)), Socket);
                char Message[48]= {010, 0, 0, 0, 0, 0, 0, 0, 0};
                if (UdpSocket->writeDatagram(Message, sizeof(Message), QHostAddress(HostInfo.addresses().at(0)), Socket)== sizeof(Message)) {
                    if (UdpSocket->waitForReadyRead()) {
                        while (UdpSocket->hasPendingDatagrams()) {
                            QByteArray QBABufferIn= UdpSocket->readAll();
                            if (QBABufferIn.size()== 48) {
                                int count= 40;
                                unsigned long DateTimeIn= uchar(QBABufferIn.at(count))+ (uchar(QBABufferIn.at(count+ 1)) << 8)+ (uchar(QBABufferIn.at(count+ 2)) << 16)+ (uchar(QBABufferIn.at(count+ 3)) << 24);
                                long tmit= ntohl((time_t)DateTimeIn);
                                tmit-= 2208988800U;
                                DateTime= QDateTime::fromTime_t(tmit);
                                Result= true;
                            }
                        }
                    }
                }
            }{
                delete UdpSocket;
            }
        }
        return Result;
    }
    

    What about it? I hope to do not have problem with it at the customers.


  • Moderators

    @mrdebug

    looks like you have a couple of paranthesis too much (see around delete UdpSocket). If it is sufficient for your purpose it is fine.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.