Sending a trap with Perl's Net::SNMP

coding_hero picture coding_hero · Jun 21, 2012 · Viewed 8.2k times · Source

I'm trying to send a trap as part of a larger Perl script. I've copied the trapsending code to another file, and am running it by itself. The code seems to think the trap sends successfully, yet I'm not seeing the trap on either machine that I have a trap listener running on.

Here's the code:

#! /usr/local/bin/perl
use strict;
use warnings;

use Net::SNMP;

#messy hardcoding
my $snmp_target = '192.168.129.50';
#my $snmp_target = '10.200.6.105'; # Server running trap listener
my $enterprise = '1.3.6.1.4.1.27002.1';

my ($sess, $err) = Net::SNMP->session(
    -hostname  => $snmp_target,
    -version => 1, #trap() requires v1
);

if (!defined $sess) {
    print "Error connecting to target ". $snmp_target . ": ". $err;
    next;
}

my @vars = qw();
my $varcounter = 1;

push (@vars, $enterprise . '.' . $varcounter);
push (@vars, OCTET_STRING);
push (@vars, "Test string");

my $result = $sess->trap(
    -varbindlist => \@vars,
    -enterprise => $enterprise,
    -specifictrap => 1,
);

if (! $result)
{
    print "An error occurred sending the trap: " . $sess->error();
}

EDIT: Added $sess->debug(255) call, here's the output:

debug: [440] Net::SNMP::Dispatcher::_event_insert(): created new head and tail [ARRAY(0x1af1fea8)]
debug: [687] Net::SNMP::Message::send(): transport address 192.168.129.50:161
debug: [2058] Net::SNMP::Message::_buffer_dump(): 70 bytes
[0000]  30 44 02 01  00 04 06 70  75 62 6C 69  63 A4 37 06   0D.....public.7.
[0016]  09 2B 06 01  04 01 81 D2  7A 01 40 04  C0 A8 81 85   .+......z.@.....
[0032]  02 01 06 02  01 01 43 01  00 30 1B 30  19 06 0A 2B   ......C..0.0...+
[0048]  06 01 04 01  81 D2 7A 01  01 04 0B 54  65 73 74 20   ......z....Test 
[0064]  73 74 72 69  6E 67                                   string
debug: [517] Net::SNMP::Dispatcher::_event_delete(): deleted [ARRAY(0x1af1fea8)], list is now empty

EDIT: Can anyone running a trap listener try this code on their machine and let me know if it works?

EDIT: Tried it from my MBP. Same result. Then noticed that the debug info says it is sending to port 161. Forced -port => 162 parameter, and it works. That leaves me with a couple of questions:

  1. Why does the trap sender default to 161?
  2. I get this error when I run with debug on. What does it mean?

    error: [97] Net::SNMP::Transport::IPv4::UDP::agent_addr(): Failed to disconnect: Address family not supported by protocol family

Answer

coding_hero picture coding_hero · Jun 28, 2012

Fixed by changing 'Port' setting from default 161 to 162.