Listen for ICMP packets in C#

前端 未结 7 854
礼貌的吻别
礼貌的吻别 2020-12-03 00:30

I have a SIP application that needs to send UDP packets to set up the SIP calls. SIP has a timeout mechanism to cope with delivery failures. An additional thing I would like

相关标签:
7条回答
  • 2020-12-03 01:01

    UPDATE: I think I'm going crazy.... That piece of code that you posted is also working for me...

    The following piece of code works fine for me(xp sp3):

    using System;
    using System.Net;
    using System.Net.Sockets;
    
    namespace icmp_capture
    {
        class Program
        {
            static void Main(string[] args)
            {            
                IPEndPoint ipMyEndPoint = new IPEndPoint(IPAddress.Any, 0);
                EndPoint myEndPoint = (ipMyEndPoint);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);            
                socket.Bind(myEndPoint);
                while (true)
                {
    
                    /*                
                    //SEND SOME BS (you will get a nice infinite loop if you uncomment this)
                    var udpClient = new UdpClient("192.168.2.199", 666);   //**host must exist if it's in the same subnet (if not routed)**              
                    Byte[] messagebyte = Encoding.Default.GetBytes("hi".ToCharArray());                
                    int s = udpClient.Send(messagebyte, messagebyte.Length);
                    */
    
                    Byte[] ReceiveBuffer = new Byte[256];
                    var nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref myEndPoint);
                    if (ReceiveBuffer[20] == 3)// ICMP type = Delivery failed
                    {
                        Console.WriteLine("Delivery failed");
                        Console.WriteLine("Returned by: " + myEndPoint.ToString());
                        Console.WriteLine("Destination: " + ReceiveBuffer[44] + "." + ReceiveBuffer[45] + "." + ReceiveBuffer[46] + "." + ReceiveBuffer[47]);
                        Console.WriteLine("---------------");
                    }
                    else {
                        Console.WriteLine("Some (not delivery failed) ICMP packet ignored");
                    }
                }
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题