The following example shows how you can design a Simple Network Time Protocol (SNTP) client. The example is ideal for devices that do not include a hardware clock.
#include <ClientConnection.h> BaTime getTime(void) { //See http://tf.nist.gov/tf-cgi/servers.cgi static const char* ntps[] = { "time.nist.gov", "time-A.timefreq.bldrdoc.gov", // If DNS is not configured in TCP/IP stack "216.171.120.36", // Random IP in pool: time.nist.gov "132.163.4.101" // Random IP in pool: time-A.timefreq.bldrdoc.gov }; int i; for(i = 0 ; i < (int)(sizeof(ntps)/sizeof(ntps[0])) ; i++) { char *ptr; int len, totLen = 0; BaTime tmpTime; int retVal=-1; ClientConnection con; ClientConnection_constructor(&con,0,0,0); if(ClientConnection_open(&con,ntps[i],37,FALSE,0,FALSE) >= 0) { ptr = (char*)&tmpTime; while(totLen < 4) { len = ClientConnection_blockRead(&con,&ptr[totLen], 4 - totLen); if(len <= 0) break; totLen += len; } ClientConnection_closeCon(&con); if(totLen == 4) { BaTime t = baNtohl(tmpTime); return t - 2208988800U; /* Convert from 1900 to 1970 format */ } } } return 0; } void printTime(void) { struct BaTm tm; BaTime t = getTime(); baTime2tm(&tm,t); printf("%d-%d-%d %d:%d:%d\n", tm.tm_year,tm.tm_mon,tm.tm_mday, tm.tm_hour,tm.tm_min,tm.tm_sec); }