Cannot receive SNMP trap on Windows 11

432 Views Asked by At

I'm using the lib SnmpSharpNet in .NET 7 with C# 10 to retreive all the snmp traps in the network. The code is almost all copied from the official documentation and work without problems on linux (Ubuntu LTS), without any modification to the system.

On windows, I'm unable to capture SNMP traps, that's a problem cause I can't debug my application using my pc.

That's the code:

using SnmpSharpNet;
    
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 162);
    EndPoint ep = (EndPoint)ipep;
    socket.Bind(ep);
    // Disable timeout processing. Just block until packet is received
    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
    bool run = true;
    int inlen = -1;
    while (run)
    {
        byte[] indata = new byte[16 * 1024];
        // 16KB receive buffer int inlen = 0;
        IPEndPoint peer = new IPEndPoint(IPAddress.Any, 0);
        EndPoint inep = (EndPoint)peer;
        try
        {
            inlen = socket.ReceiveFrom(indata, ref inep);
        }
        catch (Exception ex)
        {
            inlen = -1;
        }
        if (inlen > 0)
        {
            // Check protocol version int
            int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
            if (ver == (int)SnmpVersion.Ver1)
            {
                SnmpV1TrapPacket pkt = new SnmpV1TrapPacket();
                pkt.decode(indata, inlen);
                //Do things...
            }
            else
            {
                SnmpV2Packet pkt = new SnmpV2Packet();
                pkt.decode(indata, inlen);
                //Do things...
            }
        }
        else
        {
            if (inlen == 0)
                Trace.WriteLine("Zero length packet received.");
        }
    }

Now, first time I tried, I haven't changed any setting on windows 11, searching online, I found out that Windows 11 does not support SNMP by default, so I installed the SNMP service from the Settings > Apps > Optional functionalities > Add optional functionality but the code still not receive any trap.

1

There are 1 best solutions below

3
On

Found the solution while I was writing the question, basically, after the installation of the SNMP service from Settings > Apps > Optional functionalities > Add optional functionality, windows automatically started the "SNMP service" service and the "SNMP Traps" service and the "SNMP Traps" service was preventing other service/application to use the port 162, so I disabled it and now the code works.