新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > 嵌入式Linux网络编程之:实验内容——NTP协议实现

嵌入式Linux网络编程之:实验内容——NTP协议实现

作者: 时间:2013-09-13 来源:网络 收藏

本文引用地址://www.cghlg.com/article/257114.htm

(2)编写程序。

具体代码如下:

/*ntp.c*/

#includesys/socket.h>

#includesys/wait.h>

#includestdio.h>

#includestdlib.h>

#includeerrno.h>

#includestring.h>

#includesys/un.h>

#includesys/time.h>

#includesys/ioctl.h>

#includeunistd.h>

#includenetinet/in.h>

#includestring.h>

#includenetdb.h>

#defineNTP_PORT123/*NTP专用端口号字符串*/

#defineTIME_PORT37/*TIME/UDP端口号*/

#defineNTP_SERVER_IP210.72.145.44/*国家授时中心IP*/

#defineNTP_PORT_STR123/*NTP专用端口号字符串*/

#defineNTPV1NTP/V1/*协议及其版本号*/

#defineNTPV2NTP/V2

#defineNTPV3NTP/V3

#defineNTPV4NTP/V4

#defineTIMETIME/UDP

#defineNTP_PCK_LEN48

#defineLI0

#defineVN3

#defineMODE3

#defineSTRATUM0

#definePOLL4

#definePREC-6

#defineJAN_19700x83aa7e80/*1900年~1970年之间的时间秒数*/

#defineNTPFRAC(x)(4294*(x)+((1981*(x))>>11))

#defineUSEC(x)(((x)>>12)-759*((((x)>>10)+32768)>>16))

typedefstruct_ntp_time

{

unsignedintcoarse;

unsignedintfine;

}ntp_time;

structntp_packet

{

unsignedcharleap_ver_mode;

unsignedcharstartum;

charpoll;

charprecision;

introot_delay;

introot_dispersion;

intreference_identifier;

ntp_timereference_timestamp;

ntp_timeoriginage_timestamp;

ntp_timereceive_timestamp;

ntp_timetransmit_timestamp;

};

charprotocol[32];

/*构建包*/

intconstruct_packet(char*packet)

{

charversion=1;

longtmp_wrd;

intport;

time_ttimer;

strcpy(protocol,NTPV3);

/*判断协议版本*/

if(!strcmp(protocol,NTPV1)||!strcmp(protocol,NTPV2)

||!strcmp(protocol,NTPV3)||!strcmp(protocol,NTPV4))

{

memset(packet,0,NTP_PCK_LEN);

port=NTP_PORT;

/*设置16字节的包头*/

version=protocol[6]-0x30;

tmp_wrd=htonl((LI30)|(version27)

|(MODE24)|(STRATUM16)|(POLL8)|(PREC0xff));

memcpy(packet,tmp_wrd,sizeof(tmp_wrd));

/*设置RootDelay、RootDispersion和ReferenceIndentifier*/

tmp_wrd=htonl(116);

memcpy(packet[4],tmp_wrd,sizeof(tmp_wrd));

memcpy(packet[8],tmp_wrd,sizeof(tmp_wrd));

/*设置Timestamp部分*/

time(timer);

/*设置TransmitTimestampcoarse*/

tmp_wrd=htonl(JAN_1970+(long)timer);

memcpy(packet[40],tmp_wrd,sizeof(tmp_wrd));

/*设置TransmitTimestampfine*/

tmp_wrd=htonl((long)NTPFRAC(timer));

memcpy(packet[44],tmp_wrd,sizeof(tmp_wrd));

returnNTP_PCK_LEN;

}

elseif(!strcmp(protocol,TIME))/*TIME/UDP*/

{

port=TIME_PORT;

memset(packet,0,4);

return4;

}

return0;

}

linux操作系统文章专题:linux操作系统详解(linux不再难懂)


评论


相关推荐

技术专区

关闭