NTPクライアント(ソケット通信)

ソケット通信によりNTP(Network Time Protocol)サーバへアクセスし,現在時刻を取得する例題です.NTPサーバから送られてくる時刻は1900年1月1日0:00 (GMT) を基準にした秒数なので,プログラム内で時刻を計算するためには,1970年1月1日0:00 (UTC) を基準にした秒数に修正する必要があります.時刻の修正は,ntp_request() 関数内で行っています.

ソースのダウンロード

NTPクライアント(ソケット通信)(list_88.c)
//-----------------------------------------------------------------
// NTP クライアント(ソケット通信)
//-----------------------------------------------------------------
#include <stdio.h>
#include <time.h>
#include "ntp_lib.h"

int main(int argc, char *argv[])
{
    struct tm *tm;
    int s;             // ソケットのためのファイルディスクリプタ
    unsigned short port = 0;               // 接続するポート番号
    char host[256]      = "time.nist.gov"; // 接続するホスト名
    char tbuf[256];
    
    // サーバに接続
    if((s = ntp_open(host,port)) < 0){
        return 0;
    }
    // 受信&表示
    tm = ntp_request(s);
    strftime(tbuf,sizeof(tbuf),"%Y/%m/%d,%H:%M:%S",tm);
    puts(tbuf);

    // 後始末
    close(s);
    return 0;
}

実行結果
Gami[460]% ./myntp.exe
2005/06/08,15:01:30
Gami[461]%
inserted by FC2 system