I am using the code ntp client code at the bottom by referring the webpage on here. The code receives the time info then I would like to store the time info as YYYYMMDDHHMM
like 201304211405
. The code receives the time info from the NTP server, but I feel trouble to find out how to pass that info to the strftime
, how should I pass the received time info to the strftime
?
Here is the relevant part of the code
i=recv(s,buf,sizeof(buf),0);
tmit=ntohl((time_t)buf[10]); //# get transmit time
tmit-= 2208988800U;
printf("tmit=%d\n",tmit);
//#compare to system time
printf("Time is time: %s",ctime(&tmit));
char buffer[13];
struct tm * timeinfo;
timeinfo = ctime(&tmit);
strftime (buffer,13,"%04Y%02m%02d%02k%02M",timeinfo);
printf("new buffer:%s\n" ,buffer);
Here is the full code that I am using
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
void ntpdate();
int main() {
ntpdate();
return 0;
}
void ntpdate() {
char *hostname="79.99.6.190 2";
int portno=123; //NTP is port 123
int maxlen=1024; //check our buffers
int i; // misc var i
unsigned char msg[48]={010,0,0,0,0,0,0,0,0}; // the packet we send
unsigned long buf[maxlen]; // the buffer we get back
//struct in_addr ipaddr; //
struct protoent *proto; //
struct sockaddr_in server_addr;
int s; // socket
int tmit; // the time -- This is a time_t sort of
//use Socket;
proto=getprotobyname("udp");
s=socket(PF_INET, SOCK_DGRAM, proto->p_proto);
memset( &server_addr, 0, sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr = inet_addr(hostname);
server_addr.sin_port=htons(portno);
// send the data
i=sendto(s,msg,sizeof(msg),0,(struct sockaddr *)&server_addr,sizeof(server_addr));
/***************HERE WE START**************/
// get the data back
i=recv(s,buf,sizeof(buf),0);
tmit=ntohl((time_t)buf[10]); //# get transmit time
tmit-= 2208988800U;
printf("tmit=%d\n",tmit);
//#compare to system time
printf("Time is time: %s",ctime(&tmit));
char buffer[13];
struct tm * timeinfo;
timeinfo = ctime(&tmit);
strftime (buffer,13,"%04Y%02m%02d%02k%02M",timeinfo);
printf("new buffer:%s\n" ,buffer);
}