Exemplo n.º 1
0
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            int    recv;

            Socket     host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
            IPEndPoint iep  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0);
            EndPoint   ep   = (EndPoint)iep;

            ICMP packet = new ICMP();

            packet.Type     = 0x08;
            packet.Code     = 0x00;
            packet.Checksum = 0;

            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2);
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2);

            data = Encoding.ASCII.GetBytes("test packet");
            Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
            packet.MessageSize = data.Length + 4;
            int    packetsize = packet.MessageSize + 4;
            UInt16 chcksum    = packet.getChecksum();

            packet.Checksum = chcksum;

            host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);

            host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
            try
            {
                data = new byte[1024];
                recv = host.ReceiveFrom(data, ref ep);
                //Console.WriteLine(Encoding.ASCII.GetString(data));
            }
            catch (SocketException)
            {
                Console.WriteLine("No response from remote host");
                Console.ReadKey();
                return;
            }

            ICMP response = new ICMP(data, recv);

            Console.WriteLine("response from: {0}", ep.ToString());
            Console.WriteLine(" Type {0}", response.Type);
            Console.WriteLine(" Code: {0}", response.Code);
            int Identifier = BitConverter.ToInt16(response.Message, 0);
            int Sequence   = BitConverter.ToInt16(response.Message, 2);

            Console.WriteLine(" Identifier: {0}", Identifier);
            Console.WriteLine(" Sequence: {0}", Sequence);
            string stringData = Encoding.ASCII.GetString(response.Message, 4, response.MessageSize - 4);

            Console.WriteLine(" data: {0}", stringData);

            Console.ReadKey();
            host.Close();
        }
Exemplo n.º 2
0
    public static void Main(string[] argv)
    {
        byte[]      data = new byte[1024];
        int         recv, timestart, timestop;
        Socket      host   = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
        IPHostEntry iphe   = Dns.Resolve("www.google.ru");
        IPEndPoint  iep    = new IPEndPoint(iphe.AddressList[0], 0);
        EndPoint    ep     = iep;
        ICMP        packet = new ICMP();
        // Убрано заполнение в ICMPclass

        int packetsize = packet.MessageSize + 4;

        //ushort chcksum = packet.getChecksum();
        //packet.Checksum = packet.getChecksum();
        //packet.getChecksum();

        host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);

        int badcount = 0;

        for (int i = 1; i < 50; i++)
        {
            host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i);
            timestart = Environment.TickCount;
            host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
            try
            {
                data     = new byte[1024];
                recv     = host.ReceiveFrom(data, ref ep);
                timestop = Environment.TickCount;
                ICMP response = new ICMP(data, recv);
                if (response.Type == 11)
                {
                    Console.WriteLine("{0}            {1}            {2}ms", i, ep.ToString(), timestop - timestart);
                }
                if (response.Type == 0)
                {
                    Console.WriteLine("{0}            {1}            {2}ms.", ep.ToString(), i, timestop - timestart);
                    break;
                }
                badcount = 0;
            }
            catch (SocketException)
            {
                Console.WriteLine("{0} No response from remote host", i);
                badcount++;
                if (badcount == 5)
                {
                    Console.WriteLine("Unable to contact remote host");
                    break;
                }
            }
        }

        host.Close();
        Console.ReadLine();
    }
Exemplo n.º 3
0
    public bool TryConnect(string address)
    {
        byte[] data = new byte[1024];
        int    recv;
        Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw,
                                 ProtocolType.Icmp);

        try
        {
            IPHostEntry e = Dns.GetHostEntry(address);
            if (e == null || e.AddressList.Length == 0 || e.AddressList[0].ToString() == null)
            {
                return(false);
            }
            else
            {
                address = e.AddressList[0].ToString();
                if (address == "::1")
                {
                    address = "127.0.0.1";
                }
            }
            IPEndPoint iep    = new IPEndPoint(IPAddress.Parse(address), 0);
            EndPoint   ep     = (EndPoint)iep;
            ICMP       packet = new ICMP();

            packet.Type     = 0x08;
            packet.Code     = 0x00;
            packet.Checksum = 0;
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2);
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2);
            data = Encoding.ASCII.GetBytes("test packet");
            Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
            packet.MessageSize = data.Length + 4;
            int packetsize = packet.MessageSize + 4;

            UInt16 chcksum = packet.getChecksum();
            packet.Checksum = chcksum;

            host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
            host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
            try
            {
                data = new byte[1024];
                recv = host.ReceiveFrom(data, ref ep);
            }
            catch (SocketException)
            {
                return(false);
            }
        }
        finally
        {
            try { host.Close(); }
            catch { }
        }
        return(true);
    }
Exemplo n.º 4
0
        private void Ping()
        {
            byte[]     data = new byte[1024];
            int        recv;
            Socket     host   = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
            IPEndPoint iep    = new IPEndPoint(IPAddress.Parse(roverIPAddress), 0); //ICMP doesn't use port numbers
            EndPoint   ep     = (EndPoint)iep;
            ICMP       packet = new ICMP();

            packet.Type     = 0x08;
            packet.Code     = 0x00;
            packet.Checksum = 0;
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2);
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2);
            data = Encoding.ASCII.GetBytes("ping");
            Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
            packet.MessageSize = data.Length + 4;
            int    packetsize = packet.MessageSize + 4;
            UInt16 chcksum    = packet.getChecksum();

            packet.Checksum = chcksum;
            host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);

            while (true)
            {
                DateTime sentAt  = DateTime.Now;
                DateTime recvdAt = sentAt;
                host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                try
                {
                    data    = new byte[1024];
                    recv    = host.ReceiveFrom(data, ref ep);
                    recvdAt = DateTime.Now;
                    ICMP     response = new ICMP(data, recv);
                    DateTime recvd    = DateTime.Now;
                    ConnectedToRover = true;
                    PingRTT          = (long)(recvdAt - sentAt).TotalMilliseconds;
                }
                catch (SocketException)
                {
                    ConnectedToRover = false;
                    PingRTT          = 0;
                }

                Thread.Sleep(500);
            }
        }
Exemplo n.º 5
0
    public static void Main(string[] argv)
    {
        int trys = 3;

        Console.Write("tracert ");
        string address = Console.ReadLine();

        byte[] data = new byte[1024];
        int    recv, timestart, timestop;
        Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);

        bool flagHostEntry = false;

        while (!flagHostEntry)
        {
            try
            {
                IPHostEntry temp = Dns.GetHostEntry(address);
                flagHostEntry = true;
            }
            catch (Exception)
            {
                Console.Write("\nВведен неверный адрес, попробуйте еще раз: ");
                address = Console.ReadLine();
            };
        }
        ;

        IPHostEntry iphe   = Dns.GetHostEntry(address);
        IPEndPoint  iep    = new IPEndPoint(iphe.AddressList[0], 0);
        EndPoint    ep     = (EndPoint)iep;
        ICMP        packet = new ICMP();

        packet.Type     = 0x08;
        packet.Code     = 0x00;
        packet.Checksum = 0;
        Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 0, 2);
        Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 2, 2);
        data = Encoding.ASCII.GetBytes("test packet");
        Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
        packet.MessageSize = data.Length + 4;
        int packetsize = packet.MessageSize + 4;

        UInt16 chcksum = packet.getChecksum();

        packet.Checksum = chcksum;

        host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);

        try
        {
            if (Dns.GetHostEntry(address).HostName == address)
            {
                Console.WriteLine("\nТрассировка маршрута к {0} [{1}]", address, Dns.GetHostEntry(address).AddressList[0].ToString());
            }
            else
            {
                Console.WriteLine("\nТрассировка маршрута к {0} [{1}]", Dns.GetHostEntry(address).HostName, address);
            }
        }
        catch (Exception)
        {
            Console.WriteLine("\nТрассировка маршрута к {0}", address);
        };
        Console.WriteLine("с максимальным числом прыжков 30:\n");

        int  falsecount = 0;
        bool flagExit   = true;

        for (int i = 1; i <= 30 && flagExit; i++)
        {
            Console.Write("{0,3} ", i);
            for (int j = 0; j < trys; j++)
            {
                host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i);
                timestart = Environment.TickCount;
                host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                try
                {
                    data     = new byte[1024];
                    recv     = host.ReceiveFrom(data, ref ep);
                    timestop = Environment.TickCount;

                    ICMP response = new ICMP(data, recv);
                    if (response.Type == 11)
                    {
                        if (timestop == timestart)
                        {
                            Console.Write("    1 мс");
                        }
                        else
                        {
                            Console.Write("{0,5} мс", timestop - timestart);
                        }
                    }
                    if (response.Type == 0)
                    {
                        if (timestop == timestart)
                        {
                            Console.Write("    1 мс");
                        }
                        else
                        {
                            Console.Write("{0,5} мс", timestop - timestart);
                        }
                        flagExit = false;
                    }
                    falsecount = 0;
                }
                catch (SocketException)
                {
                    Console.Write("    *   ");
                    falsecount++;
                }
            }
            if (falsecount >= trys)
            {
                Console.WriteLine("   Превышен интервал ожидания для запроса.");
                if (falsecount == trys * 3)
                {
                    Console.WriteLine("\nНевозможно связаться с удаленным хостом.");
                    flagExit = false;
                }
            }
            else
            {
                try
                {
                    string strEndPoint = Regex.Replace(ep.ToString(), ":.*", "");
                    Console.Write("   {0} [{1}]", Dns.GetHostEntry(strEndPoint).HostName, strEndPoint);
                }
                catch (Exception)
                {
                    Console.Write("   {0}", Regex.Replace(ep.ToString(), ":.*", ""));
                };
                Console.WriteLine();
            }
        }

        host.Close();
        Console.WriteLine("\nТрассировка завершина.\n");
        Console.Read();
    }
Exemplo n.º 6
0
        static Boolean SendRecieve(int i, Socket host, ICMP packet, EndPoint ep, IPEndPoint iep, int packetsize)
        {
            int badcount = 0;

            byte[] data;
            int    pcklength;

            host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i);

            try
            {
                DateTime timestart = DateTime.Now;
                host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                data      = new byte[1024];
                pcklength = host.ReceiveFrom(data, ref ep);
                TimeSpan timestop1 = DateTime.Now - timestart;
                ICMP     response1 = new ICMP(data, pcklength);

                timestart = DateTime.Now;
                host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                data      = new byte[1024];
                pcklength = host.ReceiveFrom(data, ref ep);
                TimeSpan timestop2 = DateTime.Now - timestart;
                ICMP     response2 = new ICMP(data, pcklength);

                timestart = DateTime.Now;
                host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                data      = new byte[1024];
                pcklength = host.ReceiveFrom(data, ref ep);
                TimeSpan timestop3 = DateTime.Now - timestart;
                ICMP     response3 = new ICMP(data, pcklength);

                if (response1.Type == 11 || response2.Type == 11 || response3.Type == 11)
                {
                    Console.WriteLine(i + ": " + ep.ToString() + "     " + (timestop1.Milliseconds.ToString()) + " " + (timestop2.Milliseconds.ToString()) + " " + (timestop3.Milliseconds.ToString()) + " мс");
                    return(false);
                }

                if (response1.Type == 0 || response2.Type == 0 || response3.Type == 0)
                {
                    Console.WriteLine(i + ": " + ep.ToString() + "     достигнут за " + i + " прыжков, " + (timestop1.Milliseconds.ToString()) + " " + (timestop2.Milliseconds.ToString()) + " " + (timestop3.Milliseconds.ToString()) + " мс");
                    return(true);
                }

                return(true);
            }
            catch (SocketException)
            {
                Console.WriteLine(i + ": нет ответа от " + ep + " ( dest: " + iep + ")");
                badcount++;

                if (badcount == 4)
                {
                    Console.WriteLine("Не удалось установить соединение\n");
                    return(true);
                }
                return(false);
            }
            finally
            {
                try
                {
                    string ip = ep.ToString();
                    ip = ip.Remove(ip.Length - 2, 2);
                    if (!ip.StartsWith("192.168"))
                    {
                        IPAddress   addr  = IPAddress.Parse(ip);
                        IPHostEntry entry = Dns.GetHostEntry(addr);
                        Console.WriteLine(entry.HostName);
                    }
                    Console.WriteLine();
                }
                catch (SocketException)
                {
                    Console.WriteLine("Нет DNS ответа.\n");
                }
            }
        }
Exemplo n.º 7
0
        private void Ping()
        {
            byte[] data = new byte[1024];
            int recv;
            Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(roverIPAddress), 0); //ICMP doesn't use port numbers
            EndPoint ep = (EndPoint)iep;
            ICMP packet = new ICMP();
            packet.Type = 0x08;
            packet.Code = 0x00;
            packet.Checksum = 0;
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2);
            Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2);
            data = Encoding.ASCII.GetBytes("ping");
            Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
            packet.MessageSize = data.Length + 4;
            int packetsize = packet.MessageSize + 4;
            UInt16 chcksum = packet.getChecksum();
            packet.Checksum = chcksum;
            host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);

            while (true)
            {
                DateTime sentAt = DateTime.Now;
                DateTime recvdAt = sentAt;
                host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                try
                {
                    data = new byte[1024];
                    recv = host.ReceiveFrom(data, ref ep);
                    recvdAt = DateTime.Now;
                    ICMP response = new ICMP(data, recv);
                    DateTime recvd = DateTime.Now;
                    ConnectedToRover = true;
                    PingRTT = (long)(recvdAt - sentAt).TotalMilliseconds;
                }
                catch (SocketException)
                {
                    ConnectedToRover = false;
                    PingRTT = 0;
                }

                Thread.Sleep(500);
            }
        }
Exemplo n.º 8
0
    public static void Main(string[] argv)
    {
        byte[]     data = new byte[1024];
        int        recv, timestart, timestop;
        Socket     host   = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
        IPEndPoint iep    = new IPEndPoint(IPAddress.Parse("8.8.8.8"), 0);
        EndPoint   ep     = iep;
        ICMP       packet = new ICMP();

        packet.Type     = 0x08;
        packet.Code     = 0x00;
        packet.Checksum = 0;
        Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 0, 2);
        Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 2, 2);
        data = Encoding.ASCII.GetBytes("test packet");
        Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
        packet.MessageSize = data.Length + 4;
        int packetsize = packet.MessageSize + 4;

        UInt16 chcksum = packet.getChecksum();

        packet.Checksum = chcksum;

        host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);

        int badcount = 0;

        for (int i = 1; i < 50; i++)
        {
            host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i);
            timestart = Environment.TickCount;
            host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
            try
            {
                data     = new byte[1024];
                recv     = host.ReceiveFrom(data, ref ep);
                timestop = Environment.TickCount;
                ICMP response = new ICMP(data, recv);
                if (response.Type == 11)
                {
                    Console.WriteLine("hop {0}: response from {1}, {2}ms", i, ep.ToString(), timestop - timestart);
                }
                if (response.Type == 0)
                {
                    Console.WriteLine("{0} reached in {1} hops, {2}ms.", ep.ToString(), i, timestop - timestart);
                    break;
                }
                badcount = 0;
            }
            catch (SocketException)
            {
                Console.WriteLine("hop {0}: No response from remote host", i);
                badcount++;
                if (badcount == 5)
                {
                    Console.WriteLine("Unable to contact remote host");
                    break;
                }
            }
        }

        host.Close();
        Console.ReadKey();
    }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            string ip;

            Console.Write("tracert ");;
            ip = Console.ReadLine();
            IPAddress adress;

            if (IPAddress.TryParse(ip, out adress))
            {
                try
                {
                    string domen = System.Net.Dns.GetHostEntry(ip).HostName;
                    Console.WriteLine($"\n Трассировка маршрута к {domen}  [{ip}] \n максимальное число прыжков 30:");
                }
                catch
                {
                    Console.WriteLine($"\n Трассировка маршрута к [{ip}] \n максимальное число прыжков 30:");
                }
            }

            else
            {
                try
                {
                    string domen = System.Net.Dns.GetHostEntry(ip).HostName;
                    if (domen == ip)
                    {
                        ip = System.Net.Dns.GetHostEntry(ip).AddressList[0].ToString();
                    }
                    Console.WriteLine($"\n Трассировка маршрута к {domen}  [{ip}] \n максимальное число прыжков 30:\n");
                }
                catch
                {
                    Console.WriteLine("Не удается разрешить системное имя узла");
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }


            byte[] data = new byte[1024];

            IPAddress adr = IPAddress.Parse(ip);

            Socket      host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); //1. все адреса, используемые сокетом(протокол IPv4) 2. для передачи icmp пакетов 3. протокол icmp
            IPHostEntry iphe = System.Net.Dns.GetHostEntry(adr);                                          // контейнер для сведений об адресе веб-узлa
            IPEndPoint  iep  = new IPEndPoint(adr, 0);                                                    // конечная точка ip-адрес и номер порта
            EndPoint    ep   = (EndPoint)iep;                                                             //определяет сетевой адрес

            ICMP packet = new ICMP();                                                                     //формируем ICMP пакет

            packet.Type     = 0x08;                                                                       //тип для эхо-запроса?
            packet.Code     = 0x00;
            packet.Checksum = 0;


            int packetsize = packet.MessageSize + 8;//У кати +8 заголовка

            UInt16 chcksum = packet.getChecksum();

            packet.Checksum = chcksum;

            host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout /*промежуток времени, после которого истечет время тайм-аута*/, 3000);

            int  badcount = 0;
            bool stop     = false;


            for (int i = 1; i < 30; i++)
            {
                Console.Write(i);
                host.SetSocketOption(SocketOptionLevel.IP /*ip сокеты*/, SocketOptionName.IpTimeToLive /*поле срока жизни заголовка*/, i);

                for (int j = 1; j < 4; j++)
                {
                    DateTime timestart = DateTime.Now;

                    try
                    {
                        host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
                        data = new byte[1024];
                        int      recv     = host.ReceiveFrom(data, ref ep);// получает дейтаграмму и конечную точку источника
                        TimeSpan timestop = DateTime.Now - timestart;
                        ICMP     response = new ICMP(data, recv);

                        if (response.Type == 11)
                        {
                            Console.Write("{0,10}", (timestop.Milliseconds.ToString()) + "мс");
                        }

                        if (response.Type == 0)
                        {
                            Console.Write("{0,10}", (timestop.Milliseconds.ToString()) + "мс");
                            stop = true;
                        }

                        badcount = 0;
                    }
                    catch (SocketException)
                    {
                        Console.Write("{0,10}", "*");
                        badcount++;
                    }
                }
                if (badcount == 3 && !stop)
                {
                    Console.WriteLine("    Превышен интервал ожидания запроса");
                    badcount = 0;
                }
                else
                {
                    try
                    {
                        string domen = System.Net.Dns.GetHostEntry(IPAddress.Parse(ep.ToString().Split(':')[0])).HostName;
                        Console.WriteLine("    " + domen + "  [" + ep.ToString().Split(':')[0] + "]");
                    }
                    catch
                    {
                        Console.WriteLine("    " + ep.ToString().Split(':')[0]);
                    }
                }

                if (stop)
                {
                    Console.WriteLine("\nТрассировка завершена");
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }
            host.Close();
            Console.ReadKey();
        }