我想通过使用我自己的陷阱侦听器来获取 snmp 陷阱。事实上,我使用了在互联网上找到的代码,我添加了一些修改,现在它正在工作。我可以通过 162 端口监听。
#include "stdio.h"
#include "winsock2.h"
#pragma comment(lib, "ws2_32.lib")
#define SNMP_TRAP_PORT 162
#define MAX_MSG 400
static void init(void)
{
WSADATA wsa;
int err = WSAStartup(MAKEWORD(2, 2), &wsa);
if(err < 0)
{
puts("WSAStartup failed !");
exit(EXIT_FAILURE);
}
}
static void end(void)
{
WSACleanup();
}
int main(int argc, char *argv[]) {
int sd, rc, n, cliLen;
struct sockaddr_in cliAddr, servAddr;
char msg[MAX_MSG];
/* socket creation */
init();
sd= socket(AF_INET, SOCK_DGRAM, 0);
if(sd<0) {
printf("can't open socket \n");
exit(1);
}
/* bind local server port */
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(SNMP_TRAP_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc<0) {
printf("can't bind port number %d \n", SNMP_TRAP_PORT);
exit(1);
}
printf("waiting for SNMP Traps on UDP port %d\n", SNMP_TRAP_PORT);
/* server infinite loop */
while(1) {
/* init buffer */
memset(msg,0x0,MAX_MSG);
/* receive message */
cliLen = sizeof(cliAddr);
n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr *) &cliAddr, &cliLen);
if(n<0) {
printf("%s: cannot receive data \n",argv[0]);
continue;
}
/*message is encoded with ASN1 and should be decoded*/
/* print received message */
printf("SNMP Trap received from %s : %o\n", inet_ntoa(cliAddr.sin_addr),msg);
}/* end of server infinite loop */
end();
return 0;
}
当我收到陷阱时,代码现在可以正常工作了,我收到了一个数字。通常,我应该在 ASN1(十六进制或二进制)中得到陷阱,但我得到的是:Traplistner 结果。我想知道 12175440 是什么意思。谢谢