C#使用System.Net.NetworkInformation调试错误的traceroute

时间:2018-06-03 17:46:58

标签: c#

此源代码适用于某些网站,例如google.com,youtube.com 像codeproject.com这样的网站是阻止的,我没有任何输出

Debug>NetTraceRoute.exe codeproject.com

如果我使用带有 http:// 的arg字符串,我也会出错,并显示一些有趣的内容:

System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)

错误arg:

Unhandled Exception: System.Net.NetworkInformation.PingException: An exception o
ccurred during a Ping request. ---> System.Net.Sockets.SocketException: No such
host is known
   at System.Net.Dns.GetAddrInfo(String name)
   at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)

这是traceroute的源代码:

    // create data to send , a space character
    private const string data_send = " ";

    public static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress)
    {
        return GetTraceRoute(hostNameOrAddress, 1);
    }
    private static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress, int ttl)
    {
        Ping ping_test = new Ping();
        PingOptions ping_test_options = new PingOptions(ttl, true);
        int timeout = 1;
        byte[] buffer = Encoding.ASCII.GetBytes(data_send);
        PingReply reply = default(PingReply);

        reply = ping_test.Send(hostNameOrAddress, timeout, buffer, ping_test_options);

        List<IPAddress> result = new List<IPAddress>();
        if (reply.Status == IPStatus.Success)
        {
            result.Add(reply.Address);
        }
        else if (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut)
        {
            //add the currently returned address if an address was found with this TTL
            if (reply.Status == IPStatus.TtlExpired) result.Add(reply.Address);
            //go to get the next address to test and add to IEnumerable
            IEnumerable<IPAddress> tmp_result = default(IEnumerable<IPAddress>);
            // get temporarily result 
            tmp_result = GetTraceRoute(hostNameOrAddress, ttl + 1);
            result.AddRange(tmp_result);
        }
        else
        {
            //error 
            Console.Error.WriteLine("Error !");
        }

        return result;

0 个答案:

没有答案