Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net;
- using System.Net.Sockets;
- using System.Diagnostics;
- namespace HopCount
- {
- class Program
- {
- private static string requestText = "Host: {0}\r\nUser-Agent: test\r\nAccept: text/html";
- private static Stopwatch stopwatch = new Stopwatch();
- static void Main(string[] args)
- {
- stopwatch.Start();
- int hops = GetHops("youtube.com", 200);
- stopwatch.Stop();
- Console.WriteLine(String.Format("Počet routerů: {0}, čas: {1} ms.", hops, stopwatch.ElapsedMilliseconds));
- Console.Read();
- }
- static int GetHops(string host, int timeout)
- {
- string request = String.Format(requestText, host);
- byte[] message = Encoding.ASCII.GetBytes(request);
- IPHostEntry ipTarget = Dns.GetHostEntry(host);
- TcpClient client = new TcpClient();
- client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
- client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);
- for (int i = 1; i < 255; i++)
- {
- client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i);
- try
- {
- client.Connect(ipTarget.AddressList[0], 80);
- NetworkStream ns = client.GetStream();
- if (ns.CanWrite)
- {
- ns.Write(message, 0, message.Length);
- }
- if (ns.CanRead)
- {
- byte[] buffer = new byte[1000];
- ns.Read(buffer, 0, 1000);
- Console.WriteLine(Encoding.ASCII.GetString(buffer));
- return (i - 1);
- }
- }
- catch (SocketException se)
- {
- Console.WriteLine(se.ToString());
- }
- }
- return -1;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement