在编译期间捕获异常 [英] Exception caught during compile

查看:90
本文介绍了在编译期间捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以获得NTP通话返回的时间。但是当我运行我的代码时,程序会提示错误。以下是我的代码:



Hi, I have the following codes which will get the time returned from a NTP call. But when I run my codes, the program will prompt an error. Below are my codes:

public static DateTime GetNetworkTime()
        {
            //default Windows time server
            //asia.pool.ntp.org
            //time.windows.com
            const string ntpServer = "\\pena-db-902.ap.testing.com";

            // NTP message size - 16 bytes of the digest (RFC 2030)
            var ntpData = new byte[48];

            //Setting the Leap Indicator, Version Number and Mode values
            ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

            //error here --> SocketException was unhandled by user code [No such host is known]
            var addresses = Dns.GetHostEntry(ntpServer).AddressList; 

            //The UDP port number assigned to NTP is 123
            var ipEndPoint = new IPEndPoint(addresses[0], 123);
            //NTP uses UDP
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            socket.Connect(ipEndPoint);

            //Stops code hang if NTP is blocked
            socket.ReceiveTimeout = 10000;

            socket.Send(ntpData);
            socket.Receive(ntpData);
            socket.Close();

            //Offset to get to the "Transmit Timestamp" field (time at which the reply
            //departed the server for the client, in 64-bit timestamp format."
            const byte serverReplyTime = 40;

            //Get the seconds part
            ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

            //Get the seconds fraction
            ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

            //Convert From big-endian to little-endian
            intPart = SwapEndianness(intPart);
            fractPart = SwapEndianness(fractPart);

            var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

            //**UTC** time
            var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

            return networkDateTime.ToUniversalTime();
        }

推荐答案

首先,互联网地址使用/不是\



其次,当使用套接字时,你不需要//前缀。



第三,尝试ping你的地址以查看它是否存在。



四,转到: http://www.ntp.org/ [ ^ ]
First, internet address use / not \

Second, when using sockets you don't need the // prefix.

Third, try pinging your address to see if it exists first.

Fourth, goto : http://www.ntp.org/[^]


这篇关于在编译期间捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆