Reputation: 31
i'm using snmp4j to capture trap data from multiple routers,but i don't know how to receive the source IP address from these routers, which router is the sender. That's my code below, maybe it's useful:
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());
}
}
Upvotes: 3
Views: 1759
Reputation: 377
The CommandResponderEvent contains the sender address in the getPeerAddress() member: See http://www.snmp4j.org/doc/org/snmp4j/CommandResponderEvent.html#getPeerAddress()
If the trap was forwarded by a proxy, the snmpTrapAddress.0 variable binding (defined in the SNMP-COMMUNITY-MIB, RFC3584) will contain the address of the original trap sender.
Upvotes: 2