新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 嵌入式Linux網(wǎng)絡(luò)編程之:實(shí)驗(yàn)內(nèi)容——NTP協(xié)議實(shí)現(xiàn)

嵌入式Linux網(wǎng)絡(luò)編程之:實(shí)驗(yàn)內(nèi)容——NTP協(xié)議實(shí)現(xiàn)

作者: 時(shí)間:2013-09-13 來源:網(wǎng)絡(luò) 收藏

本文引用地址:http://2s4d.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專用端口號(hào)字符串*/

#defineTIME_PORT37/*TIME/UDP端口號(hào)*/

#defineNTP_SERVER_IP210.72.145.44/*國家授時(shí)中心IP*/

#defineNTP_PORT_STR123/*NTP專用端口號(hào)字符串*/

#defineNTPV1NTP/V1/*協(xié)議及其版本號(hào)*/

#defineNTPV2NTP/V2

#defineNTPV3NTP/V3

#defineNTPV4NTP/V4

#defineTIMETIME/UDP

#defineNTP_PCK_LEN48

#defineLI0

#defineVN3

#defineMODE3

#defineSTRATUM0

#definePOLL4

#definePREC-6

#defineJAN_19700x83aa7e80/*1900年~1970年之間的時(shí)間秒數(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)建包*/

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不再難懂)


評(píng)論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉