Search code examples
c#sharppcap

How to get continuous packet by Sharppcap?


I am currently trying to capture an EtherCAT packet sent and received via a program called TwinCAT. TwinCAT is real-time control software for EtherCAT communication on Windows. This program is used to communicate with slaves every 4ms.

By the way, I captured packets and observed that the data wasn't continuous during the analysis. So, I inserted the code to check the time difference in the part capturing the packet, and it was confirmed that some packets are packets 20ms later than the previous packet.

Since I can check the Lost Frame in the TwinCAT XAE Tool, I don't think the packet is actually missing, and I think there is a problem with my program.

Below is my code.

public class EtherCATPacketCaptureService
{
    private const int PacketQueueSize = 1024;

    private object locker;  //<-Mutex
    private Queue<RawCapture> PacketQueue;  //<-패킷을 저장할 큐
    private WinPcapDevice _etherCATDevice;  //<-EtherCAT 통신 네트워크 장치

    public int PacketsCount { get => PacketQueue.Count; }

    //생성자 : _etherCATDevice 객체와 EtherCAT통신장치 매칭 
    public EtherCATPacketCaptureService(string etherCATNICAddr)
    {
        CaptureDeviceList devices = CaptureDeviceList.Instance;

        if (devices.Count() < 1)
        {
            throw new Exception("Not exist network interface");
        }

        foreach (WinPcapDevice dev in devices)
        {
            if (dev.Addresses.Count > 0)
            {
                foreach (PcapAddress addr in dev.Addresses)
                {
                    if (addr.Addr.hardwareAddress != null)
                    {
                        string HWAddr = addr.Addr.hardwareAddress.ToString();
                        if (HWAddr == etherCATNICAddr)  // EtherCAT NIC MAC주소를 EtherCATNICAddr파라미터로 넘겨받아 설정
                        {
                            _etherCATDevice = dev;
                        }
                    }
                }
            }
        }

        if (_etherCATDevice == null)
            throw new NullReferenceException("Can't find EtherCAT NIC");
        else
        {
            PacketQueue = new Queue<RawCapture>(PacketQueueSize);
            locker = new object();
            _etherCATDevice.OnPacketArrival += Device_OnPacketArrival;
            _etherCATDevice.Open(OpenFlags.Promiscuous, 1000);
        }
    }

    ~EtherCATPacketCaptureService()
    {
        _etherCATDevice.Close();
    }

    //패킷 캡쳐 시작
    public void StartCapture(int timeout)
    {
        if(_etherCATDevice != null)
        {
            _etherCATDevice.StartCapture();
        }
    }

    //패킷 캡쳐 종료
    public void StopCapture()
    {
        if (_etherCATDevice != null)
        {
            _etherCATDevice.StopCapture();
        }
    }

    //패킷캡쳐 이벤트 발생 시 패킷을 큐메모리에 저장
    private void Device_OnPacketArrival(object sender, SharpPcap.CaptureEventArgs e)
    {
        if (_etherCATDevice != null)
        {
            lock (locker)
            {
                if (PacketQueue != null)
                {
                    if (PacketQueue.Count > 0)
                    {
                        if((e.Packet.Timeval.Date.Ticks - PacketQueue.Peek().Timeval.Date.Ticks) > 200000)
                            throw new Exception("Packet Droped");
                    }
                    PacketQueue.Enqueue(e.Packet);
                }
            }
        }
    }

    //저장된 패킷을 리턴(Dequeue)
    public RawCapture[] GetPackets(int count)
    {
        RawCapture[] PacketArray;
        if (_etherCATDevice != null)
        {
            lock (locker)
            {
                if (count >= PacketQueue.Count)
                    PacketArray = new RawCapture[PacketQueue.Count];
                else
                    PacketArray = new RawCapture[count];

                for (int i = 0; i < PacketArray.Length; i++)
                {
                    PacketArray[i] = PacketQueue.Dequeue();
                }
            }
            return PacketArray;
        }
        else
            return null;
    }

    public RawCapture[] GetPackets()
    {
        RawCapture[] PacketArray;
        if (_etherCATDevice != null)
        {
            lock (locker)
            {
                PacketArray = new RawCapture[PacketQueue.Count];

                for (int i = 0; i < PacketArray.Length; i++)
                {
                    PacketArray[i] = PacketQueue.Dequeue();
                }
            }
            return PacketArray;
        }
        else
            return null;
    }

    //저장된 패킷 클리어
    public void ClearPackets()
    {
        lock (locker)
        {
            PacketQueue.Clear();
        }
    }
}

The event handler for the OnPacketArrival is Device_OnPacketArrival, which detects the problem by causing an exception to be thrown if it finds a difference of 20ms or more in the handler compared to the time of the previous packet.

Is this a problem that happens because my performance is bad? Can performance improvements be solved? If you have a good opinion, please reply.


Solution

  • If you are not programming this just for fun or with educational purposes in mind but for professional use, I suggest you analyze the Ethercat packets of your machines with Wireshark and an additional hardware called ET2000.

    The ET2000 adds a timestamp, with a max. delay of 40ns, to the mirrored packet sent to the pc, which you will be able to read thanks to the EtherCAT Stack Link dissector in wireshark.