嵌入式Linux網(wǎng)絡編程之:實驗內容——NTP協(xié)議實現(xiàn)
/*獲取NTP時間*/
intget_ntp_time(intsk,structaddrinfo*addr,structntp_packet*ret_time)
{
fd_setpending_data;
structtimevalblock_time;
chardata[NTP_PCK_LEN*8];
intpacket_len,data_len=addr->ai_addrlen,count=0,result,i,re;
if(!(packet_len=construct_packet(data)))
{
return0;
}
/*客戶端給服務器端發(fā)送NTP協(xié)議數(shù)據(jù)包*/
if((result=sendto(sk,data,
packet_len,0,addr->ai_addr,data_len))0)
{
perror(sendto);
return0;
}
/*調用select()函數(shù),并設定超時時間為1s*/
FD_ZERO(pending_data);
FD_SET(sk,pending_data);
block_time.tv_sec=10;
block_time.tv_usec=0;
if(select(sk+1,pending_data,NULL,NULL,block_time)>0)
{
/*接收服務器端的信息*/
if((count=recvfrom(sk,data,
NTP_PCK_LEN*8,0,addr->ai_addr,data_len))0)
{
perror(recvfrom);
return0;
}
if(protocol==TIME)
{
memcpy(ret_time->transmit_timestamp,data,4);
return1;
}
elseif(countNTP_PCK_LEN)
{
return0;
}
/*設置接收NTP包的數(shù)據(jù)結構*/
ret_time->leap_ver_mode=ntohl(data[0]);
ret_time->startum=ntohl(data[1]);
ret_time->poll=ntohl(data[2]);
ret_time->precision=ntohl(data[3]);
ret_time->root_delay=ntohl(*(int*)(data[4]));
ret_time->root_dispersion=ntohl(*(int*)(data[8]));
ret_time->reference_identifier=ntohl(*(int*)(data[12]));
ret_time->reference_timestamp.coarse=ntohl*(int*)(data[16]));
ret_time->reference_timestamp.fine=ntohl(*(int*)(data[20]));
ret_time->originage_timestamp.coarse=ntohl(*(int*)(data[24]));
ret_time->originage_timestamp.fine=ntohl(*(int*)(data[28]));
ret_time->receive_timestamp.coarse=ntohl(*(int*)(data[32]));
ret_time->receive_timestamp.fine=ntohl(*(int*)(data[36]));
ret_time->transmit_timestamp.coarse=ntohl(*(int*)(data[40]));
ret_time->transmit_timestamp.fine=ntohl(*(int*)(data[44]));
return1;
}/*endofifselect*/
return0;
}
linux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)
評論