블로그 이미지
랜달프

calendar

1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Notice

    2009. 3. 18. 19:20 Programming/C programming

    우리가 흔히 리눅스에서

    rdate -s time.bora.net

    이라는 명령어로 시간을 맞춘다

    즉,     time.bora.net   이라는 타임 서버에서 프로토콜에 맞춰 값을 가져온 후 시스템에 적용 하는 것이다.
    다음은 RFC 868 문서를 보고 만든 것인데 time.bora.net 서버에서 시간을 가져와 출력하는 코드이다.
    #ifdef _WIN32
    #include 
    #else
    #include 
    #include 
    #include 
    #include 
    #endif
    
    #include 
    #include 
    
    
    std::time_t getTime()
    {
    #ifdef _WIN32
    	WSADATA wsaData;
    #endif
    
    	int hSocket;
    	sockaddr_in servAddr;
    	std::time_t	sBuffer;
    	struct hostent* s_HostEntry;    
    	int strLen;
    	
    #ifdef _WIN32
    	if( WSAStartup(MAKEWORD(1,1),&wsaData) != 0 )
    	{
    		std::cout << "Startup Error" << std::endl;
    		return -1;
    	}
    #endif
    
    	hSocket = socket(PF_INET, SOCK_STREAM, 0);
    	
    	if( -1 == hSocket )
    	{
    		std::cout << "Socket Create Error" << std::endl;
    		return -1;
    	}
    
    	memset(&servAddr, 0, sizeof(servAddr));
    	servAddr.sin_family = AF_INET;
    	servAddr.sin_port = htons(37);
    
    	s_HostEntry = gethostbyname("time.bora.net");
    	memcpy((void *)(&servAddr.sin_addr), (void *)(s_HostEntry->h_addr), sizeof(servAddr.sin_addr));
    
    	if ( -1 == connect(hSocket, (sockaddr*)&servAddr, sizeof(servAddr)) )
    	{
    		return -1;
    	}
    
    	strLen = recv(hSocket, (char*)&sBuffer, sizeof(sBuffer), 0);
    	
    
    	if( -1 == strLen )
    	{
    		return -1;
    	}
    
    	sBuffer = ntohl(sBuffer) - 2208988800l;
    
    #ifdef _WIN32
    	closesocket(hSocket);
    	WSACleanup();
    #else
    	close(hSocket);
    #endif
    
    	return sBuffer;
    }
    
    int main()
    {
    	std::time_t currentTime;
    	std::tm* ts;
    	char str_time[80];
    
    	currentTime = getTime();
    	ts = localtime(¤tTime);      // 시스템에 적용된 시간대로 tm 구조체에 저장  (대한민국 표준시 GMT +09:00 )
    	//ts = gmtime(¤tTime);     // GMT  
    
    	strftime(str_time, 80, "%Y년 %m월 %d일 %H:%M:%S  %Z", ts);  // tm 구조체를 문자열로 저장
    
    	std::cout << str_time << std::endl;
    	
    	return 0;
    }
    
    struct tm 구조체
    #include 
    struct tm {
    
    	int tm_sec;   /* 초 */
    	int tm_min;   /* 분 */
    	int tm_hour;  /* 시 (0--23) */
    	int tm_mday;  /* 일 (1--31) */
    	int tm_mon;   /* 월 (0--11) */
    	int tm_year;  /* 년 (+ 1900) */
    	int tm_wday;  /* 요일 (0--6; 일요일 = 0) */
    	int tm_yday;  /* 올해 몇번째 날 (0--365) */
    	int tm_isdst; /* 서머타임 여부 */
    
    };
    

    실행 화면

    posted by 랜달프