Advertisement
Guest User

ttl stuff

a guest
Oct 12th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Diagnostics;
  9.  
  10. namespace HopCount
  11. {
  12.     class Program
  13.     {
  14.         private static string requestText = "Host: {0}\r\nUser-Agent: test\r\nAccept: text/html";
  15.         private static Stopwatch stopwatch = new Stopwatch();
  16.  
  17.         static void Main(string[] args)
  18.         {
  19.             stopwatch.Start();
  20.             int hops = GetHops("youtube.com", 200);
  21.             stopwatch.Stop();
  22.             Console.WriteLine(String.Format("Počet routerů: {0}, čas: {1} ms.", hops, stopwatch.ElapsedMilliseconds));
  23.             Console.Read();
  24.  
  25.         }
  26.  
  27.         static int GetHops(string host, int timeout)
  28.         {
  29.            
  30.             string request = String.Format(requestText, host);
  31.             byte[] message = Encoding.ASCII.GetBytes(request);
  32.  
  33.             IPHostEntry ipTarget = Dns.GetHostEntry(host);
  34.             TcpClient client = new TcpClient();
  35.  
  36.             client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
  37.             client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);
  38.  
  39.  
  40.             for (int i = 1; i < 255; i++)
  41.             {
  42.                 client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i);
  43.  
  44.                 try
  45.                 {
  46.                     client.Connect(ipTarget.AddressList[0], 80);
  47.  
  48.                     NetworkStream ns = client.GetStream();
  49.  
  50.                     if (ns.CanWrite)
  51.                     {
  52.                         ns.Write(message, 0, message.Length);
  53.                     }
  54.  
  55.                     if (ns.CanRead)
  56.                     {
  57.                         byte[] buffer = new byte[1000];
  58.                         ns.Read(buffer, 0, 1000);
  59.                         Console.WriteLine(Encoding.ASCII.GetString(buffer));
  60.  
  61.                         return (i - 1);
  62.                     }
  63.  
  64.                 }
  65.                 catch (SocketException se)
  66.                 {
  67.                     Console.WriteLine(se.ToString());
  68.                 }
  69.             }
  70.  
  71.             return -1;
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement