如何使用snmp4j从多个snmp陷阱接收源IP地址

时间:2016-04-25 14:50:31

标签: java snmp snmp4j

我使用snmp4j从多个路由器捕获陷阱数据,但我不知道如何从这些路由器接收源IP地址,哪个路由器是发送方。这是我下面的代码,也许它很有用:

public class SNMPTrapReceiver implements CommandResponder {

private MultiThreadedMessageDispatcher dispatcher;
private Snmp snmp = null;
private Address listenAddress;
private ThreadPool threadPool;
private int n = 0;

public SNMPTrapReceiver() {
}

public static void main(String[] args) {
    new SNMPTrapReceiver().run();
}

private void run() {
    try {
        init();
        snmp.addCommandResponder(this);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

private void init() throws UnknownHostException, IOException {
    threadPool = ThreadPool.create("Trap", 10);
    dispatcher = new MultiThreadedMessageDispatcher(threadPool,
            new MessageDispatcherImpl());
    listenAddress = GenericAddress.parse(System.getProperty(
            "snmp4j.listenAddress", "udp:0.0.0.0/162"));
    TransportMapping<?> transport;
    if (listenAddress instanceof UdpAddress) {
        transport = new DefaultUdpTransportMapping(
                (UdpAddress) listenAddress);
    } else {
        transport = new DefaultTcpTransportMapping(
                (TcpAddress) listenAddress);
    }
    USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
            MPv3.createLocalEngineID()), 0);
    usm.setEngineDiscoveryEnabled(true);

    snmp = new Snmp(dispatcher, transport);
    snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
    snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
    snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3(usm));
    SecurityModels.getInstance().addSecurityModel(usm);
    snmp.getUSM().addUser(
            new OctetString("MD5DES"),
            new UsmUser(new OctetString("MD5DES"), AuthMD5.ID,
                    new OctetString("UserName"), PrivDES.ID,
                    new OctetString("PasswordUser")));
    snmp.getUSM().addUser(new OctetString("MD5DES"),
            new UsmUser(new OctetString("MD5DES"), null, null, null, null));

    snmp.listen();
}

public void processPdu(CommandResponderEvent event) {
    StringBuffer msg = new StringBuffer();
    msg.append(event.toString());
    Vector<? extends VariableBinding> varBinds = event.getPDU()
            .getVariableBindings();
    if (varBinds != null && !varBinds.isEmpty()) {
        Iterator<? extends VariableBinding> varIter = varBinds.iterator();
        while (varIter.hasNext()) {
            VariableBinding var = varIter.next();
            msg.append(var.toString()).append(";");
        }
    }
    System.out.println("Message Received: " + msg.toString());
}

}

1 个答案:

答案 0 :(得分:2)

CommandResponderEvent包含getPeerAddress()成员中的发件人地址: 见http://www.snmp4j.org/doc/org/snmp4j/CommandResponderEvent.html#getPeerAddress()

如果陷阱是由代理转发的,则snmpTrapAddress.0变量绑定(在SNMP-COMMUNITY-MIB中定义,RFC3584)将包含原始陷阱发送方的地址。