Skip to content

C# 시스템 시간 동기화 - time.window.com

by CroitzK posted May 05, 2020 Views 177 Likes 0 Replies 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

# 취득 메소드

        /// <summary>
        /// Gets the current DateTime from time-a.nist.gov.
        /// </summary>
        /// <returns>A DateTime containing the current time.</returns>
        public static DateTime GetNetworkTime()
        {
            return GetNetworkTime("time.windows.com"); // time-a.nist.gov
        }

        /// <summary>
        /// Gets the current DateTime from <paramref name="ntpServer"/>.
        /// </summary>
        /// <param name="ntpServer">The hostname of the NTP server.</param>
        /// <returns>A DateTime containing the current time.</returns>
        public static DateTime GetNetworkTime(string ntpServer)
        {
            IPAddress[] address = Dns.GetHostEntry(ntpServer).AddressList;

            if (address == null || address.Length == 0)
                throw new ArgumentException("Could not resolve ip address from '" + ntpServer + "'.", "ntpServer");

            IPEndPoint ep = new IPEndPoint(address[0], 123);

            return GetNetworkTime(ep);
        }

        /// <summary>
        /// Gets the current DateTime form <paramref name="ep"/> IPEndPoint.
        /// </summary>
        /// <param name="ep">The IPEndPoint to connect to.</param>
        /// <returns>A DateTime containing the current time.</returns>
        public static DateTime GetNetworkTime(IPEndPoint ep)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            s.Connect(ep);

            byte[] ntpData = new byte[48]; // RFC 2030 
            ntpData[0] = 0x1B;
            for (int i = 1; i < 48; i++)
                ntpData[i] = 0;

            s.Send(ntpData);
            s.Receive(ntpData);

            byte offsetTransmitTime = 40;
            ulong intpart = 0;
            ulong fractpart = 0;

            for (int i = 0; i <= 3; i++)
                intpart = 256 * intpart + ntpData[offsetTransmitTime + i];

            for (int i = 4; i <= 7; i++)
                fractpart = 256 * fractpart + ntpData[offsetTransmitTime + i];

            ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
            s.Close();

            TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);

            DateTime dateTime = new DateTime(1900, 1, 1);
            dateTime += timeSpan;

            TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
            DateTime networkDateTime = (dateTime + offsetAmount);

            return networkDateTime.AddHours(-9);
        }


#설정 메소드

        [DllImport("kernel32")]
        public static extern int SetSystemTime(ref SYSTEMTIME lpSystemTime);


        public struct SYSTEMTIME
        {
            public short wYear; //년도
            public short wMonth; //월
            public short wDayOfWeek; //요일
            public short wDay; //일
            public short wHour; //시
            public short wMinute; //분
            public short wSecond; //초
            public short wMilliseconds; //1/100초
        }

        private void setNowTime()
        {
            SYSTEMTIME sTime = new SYSTEMTIME();
            sTime.wYear = Convert.ToInt16(GetNetworkTime().Year);
            sTime.wMonth = Convert.ToInt16(GetNetworkTime().Month);
            sTime.wDayOfWeek = Convert.ToInt16(GetNetworkTime().DayOfWeek);
            sTime.wDay = Convert.ToInt16(GetNetworkTime().Day);
            sTime.wHour = Convert.ToInt16(GetNetworkTime().Hour);
            sTime.wMinute = Convert.ToInt16(GetNetworkTime().Minute);
            sTime.wSecond = Convert.ToInt16(GetNetworkTime().Second);
            sTime.wMilliseconds = Convert.ToInt16(GetNetworkTime().Millisecond);
            SetSystemTime(ref sTime);
        }



?

Calender

2020.12
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    

Time Info

Counter Info

방문자수

전체 : 50,673
오늘 : 12
어제 : 32

페이지뷰

전체 : 1,782,065
오늘 : 57
어제 : 1,231

COPYRIGHT 2009 by AGMServer.com

Powered by Xpress Engine / Designed by Sketchbook

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소