Reputation: 13
SnmpV3 uses socket for the information I need to get. This is the information I should get, but (int inlen = socket.ReceiveFrom (inbuffer, SocketFlags.None, ref peer); the application stops at this sentence.how can i get this information?
// We'll need a byte buffer to store incoming data
byte[] inbuffer = new byte[32 * 1024];
// End point details of the host we received packet(s) from
EndPoint peer = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
// Create a IP/UDP socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);
// Bind the socket to the standard snmptrapd port = udp/162
socket.Bind((EndPoint)new IPEndPoint(IPAddress.Any, 162));
// Wait for a packet
int inlen = socket.ReceiveFrom(inbuffer, SocketFlags.None, ref peer);
// Make sure we received some data instead of an empty packet.
if (inlen== 0 )
{
Console.WriteLine("Received an invalid SNMP packet length 0 Bytes.");
socket.Close();
return;
}
Upvotes: 0
Views: 72
Reputation: 223
Read the documentation. This is a blocking operation. That means execution of the thread is halted until the method returns.
If no data is available for reading, the ReceiveFrom method will block until data is available. If you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the ReceiveFrom method will complete immediately and throw a SocketException. You can use the Available property to determine if data is available for reading. When Available is non-zero, retry the receive operation.
https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.receivefrom?view=netcore-3.1
To prevent this, you can run this operation on a dedicated background thread or use the socket class asynchronous methods.
BeginReceiveFrom
:
ReceiveFromAsync
:
Upvotes: 2