嵌入式linux自動更新網絡時間NTP實踐

    嵌入式設備中,有些需要得到實時的比較準確的時間,以和服務器或是設備之間進行時間同步,但是很多嵌入式設備又不能通過人工設置時間的方式來同步時間,需要自動從網絡上獲取時間,這就需要用到NTP。NTP是網絡時間協議(Network Time Protocol)的簡稱,它是用來同步網絡中各個計算機設備的時間的協議。目前有第三方的代碼可以支持NTP,本文講訴ntpclient的用法。

    ntpclient is an NTP(RFC-1305)client for unix-alike computers.Its functionality is a small subset of xntpd,but IMHO performs better (or at least has the potential tofunction better) within that limited scope. Since it is muchsmaller than xntpd, it is also more relevant for embedded computers.

    ntpclient的下載地址是: ntpclient下載地址  

    下載好後,進行交叉編譯後放入設備中運行就可以了,運行命令如:ntpclient -d -s -g -c 1 -h time.nist.gov

    但是如果你需要將ntpclient整合到你自己的代碼裏面中,需要怎麼做呢,其實也很簡單,下載源代碼後,例如我下載的是ntpclient_2010_365.tar.gz,解壓tar -zxvf ntpclient_2010_365.tar.gz,解壓後將ntpclient.c,ntpclient.h,phaselock.c這三個文件放入你的項目中,更改ntpclient.c中的main()函數即可。

    我的更改如下:

void ntp_test(void) 
{
	int usd;  /* socket */
	int c;
	/* These parameters are settable from the command line
	   the initializations here provide default behavior */
	short int udp_local_port=0;   /* default of 0 means kernel chooses */
	char *hostname=NULL;          /* must be set */
	int initial_freq;             /* initial freq value to use */
	struct ntp_control ntpc;
	ntpc.live=0;
	ntpc.set_clock=0;
	ntpc.probe_count=0;           /* default of 0 means loop forever */
	ntpc.cycle_time=600;          /* seconds */
	ntpc.goodness=0;
	ntpc.cross_check=1;
    //hostname = "210.72.145.44"; //中國國家授時中心
    //hostname = "ntp.sjtu.edu.cn"; //上海交通大學NTP服務器,202.120.2.101


	(ntpc.set_clock)++;
	ntpc.probe_count = 1;
	hostname = "time.nist.gov";
	
	if (ntpc.set_clock && !ntpc.live && !ntpc.goodness && !ntpc.probe_count) {
		ntpc.probe_count = 1;
	}

	/* respect only applicable MUST of RFC-4330 */
	if (ntpc.probe_count != 1 && ntpc.cycle_time < MIN_INTERVAL) {
		ntpc.cycle_time = MIN_INTERVAL;
	}

		printf("Configuration:\n"
		"  -c probe_count %d\n"
		"  -d (debug)     %d\n"
		"  -g goodness    %d\n"
		"  -h hostname    %s\n"
		"  -i interval    %d\n"
		"  -l live        %d\n"
		"  -p local_port  %d\n"
		"  -q min_delay   %f\n"
		"  -s set_clock   %d\n"
		"  -x cross_check %d\n",
		ntpc.probe_count, debug, ntpc.goodness,
		hostname, ntpc.cycle_time, ntpc.live, udp_local_port, min_delay,
		ntpc.set_clock, ntpc.cross_check );

	/* Startup sequence */
	if ((usd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==-1)
	{
		printf ("ntp socket error!\n");
	}

	setup_receive(usd, INADDR_ANY, udp_local_port);

	setup_transmit(usd, hostname, NTP_PORT, &ntpc);

	primary_loop(usd, &ntpc);

	close(usd);
}

    編譯運行,在需要的地方調用就可以了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章