2013-04-21 80 views
2

我通過引用here上的網頁在底部使用代碼ntp客戶端代碼。代碼接收時間信息,然後我想將時間信息存儲爲YYYYMMDDHHMM,如201304211405。代碼接收來自NTP服務器的時間信息,但是我很難找到如何將該信息傳遞給strftime,我應該如何將接收到的時間信息傳遞給strftime從NTP服務器向strftime函數傳遞時間信息

下面是代碼

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); 

這裏的相關部分,我使用

#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); 
} 
+0

是您的代碼工作的替換線? – mohit 2013-04-21 18:30:06

+0

它正在工作,但'strftime'是錯誤的,將錯誤的數據傳遞到'char緩衝區[13]' – sven 2013-04-21 18:33:36

回答

1

的問題是與線的完整代碼...

timeinfo = ctime(&tmit); 

如果timeinfostruct tm *類型,則不能將其指向char *人類可讀的字符串由ctime()返回。

如果你轉換爲struct tm *,你需要爲使用gmtime()localtime(),這取決於你是否希望struct tm *是UTC時間,或表示相對於本地時區。

由於ctime()使用本地時區,我會認爲你想這樣,所以用...

timeinfo = localtime(&tmit); 
+0

'localtime'和'gmtime'從本地系統獲取時間?我想將時間信息傳遞給從'tmit'存儲的NTP服務器獲取的'buffer'。我的問題是如何做到這一點 – sven 2013-04-21 18:55:04

+0

@sven查看更新的答案。 – Aya 2013-04-21 18:58:23

+0

謝謝Aya的幫助! – sven 2013-04-21 19:12:14

相關問題