【问题标题】:passing time info from NTP server to strftime function将时间信息从 NTP 服务器传递到 strftime 函数
【发布时间】:2013-04-21 18:21:03
【问题描述】:

我通过引用here 上的网页,使用底部的代码ntp 客户端代码。该代码接收时间信息,然后我想将时间信息存储为YYYYMMDDHHMM,如201304211405。该代码从 NTP 服务器接收时间信息,但我不知道如何将该信息传递给 strftime,我应该如何将收到的时间信息传递给 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);
}

【问题讨论】:

  • 你的代码有效吗?
  • 它正在工作,但strftime 将错误的数据传递给char buffer[13] 是错误的

标签: c linux posix strftime


【解决方案1】:

问题出在线路上……

timeinfo = ctime(&tmit);

如果timeinfostruct tm * 类型,则不能只将其指向ctime() 返回的char * 人类可读字符串。

如果您要转换为struct tm *,则需要使用gmtime()localtime(),具体取决于您希望struct tm * 是UTC 时间,还是相对于您的本地时区表示.

由于ctime() 使用本地时区,我假设您希望这样,所以将该行替换为...

timeinfo = localtime(&tmit);

【讨论】:

  • localtimegmtime 从本地系统获取时间?我想将时间信息传递给buffer,这是从tmit 存储的NTP 服务器获取的。我的问题是如何做到这一点
  • 感谢阿雅的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多