嵌入式Linux網(wǎng)絡(luò)編程之:實驗內(nèi)容——NTP協(xié)議實現(xiàn)
(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/*協(xié)議及其版本號*/
#defineNTPV2NTP/V2
#defineNTPV3NTP/V3
#defineNTPV4NTP/V4
#defineTIMETIME/UDP
#defineNTP_PCK_LEN48
#defineLI0
#defineVN3
#defineMODE3
#defineSTRATUM0
#definePOLL4
#definePREC-6
#defineJAN_19700x83aa7e80/*1900年~1970年之間的時間秒數(shù)*/
#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];
/*構(gòu)建NTP協(xié)議包*/
intconstruct_packet(char*packet)
{
charversion=1;
longtmp_wrd;
intport;
time_ttimer;
strcpy(protocol,NTPV3);
/*判斷協(xié)議版本*/
if(!strcmp(protocol,NTPV1)||!strcmp(protocol,NTPV2)
||!strcmp(protocol,NTPV3)||!strcmp(protocol,NTPV4))
{
memset(packet,0,NTP_PCK_LEN);
port=NTP_PORT;
/*設(shè)置16字節(jié)的包頭*/
version=protocol[6]-0x30;
tmp_wrd=htonl((LI30)|(version27)
|(MODE24)|(STRATUM16)|(POLL8)|(PREC0xff));
memcpy(packet,tmp_wrd,sizeof(tmp_wrd));
/*設(shè)置RootDelay、RootDispersion和ReferenceIndentifier*/
tmp_wrd=htonl(116);
memcpy(packet[4],tmp_wrd,sizeof(tmp_wrd));
memcpy(packet[8],tmp_wrd,sizeof(tmp_wrd));
/*設(shè)置Timestamp部分*/
time(timer);
/*設(shè)置TransmitTimestampcoarse*/
tmp_wrd=htonl(JAN_1970+(long)timer);
memcpy(packet[40],tmp_wrd,sizeof(tmp_wrd));
/*設(shè)置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操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)
評論