使用snmp4j实现Snmp功能(二)
前一篇文章講了如何用snmp4j實現set和get的功能,今天講如何接收trap。
snmp4j提供了一個抽象類CommandResponder類用于接收trap,這個類里面有一個必須實現的方法processPdu(),當接收到trap,會自動進入這個方法,因此我們可以將對trap的處理寫在這里。
下面修改上篇文章例子中的initComm()方法
private TransportMapping transport = null;public void initComm() throws IOException {// 設置Agent方的IP和端口targetAddress = GenericAddress.parse("udp:192.168.1.1/161");// 設置接收trap的IP和端口transport = new DefaultUdpTransportMapping(new UdpAddress("192.168.1.2/162"));snmp = new Snmp(transport);CommandResponder trapRec = new CommandResponder() {public synchronized void processPdu(CommandResponderEvent e) {// 接收trapPDU command = e.getPDU();if (command != null) {System.out.println(command.toString());}}};snmp.addCommandResponder(trapRec);transport.listen();}其中targetAddress指Agent端也就是trap發送,transport指trap接收方,這里就是本機,假設IP是192.168.1.2,但注意不能寫成127.0.0.1。
因為我們無法得知trap什么時候會發送,所以需要有一個線程等待trap的到來,在這個例子中我們使用wait()來等待trap的到來,具體應用中就要根據實際情況來做了
public synchronized void listen() {System.out.println("Waiting for traps..");try {this.wait();//Wait for traps to come in} catch (InterruptedException ex) {System.out.println("Interrupted while waiting for traps: " + ex);System.exit(-1);}}public static void main(String[] args) {try {SnmpUtil util = new SnmpUtil();util.initComm();util.listen();} catch (IOException e) {e.printStackTrace();}}?
將上面的代碼添加到原來的例子中,就可以接收trap了。
但是還有一個問題,如何讓192.168.1.1發送trap呢?這個也可以使用snmp4j來做。其實發送trap和發送set、get PDU是類似的,同樣是發送PDU,只不過類型不一樣。我們把前面的例子復制到192.168.1.1,在里面添加一段代碼
public void setTrap() throws IOException {// 構造Trap PDUPDU pdu = new PDU();pdu.add(new VariableBinding(new OID(".1.3.6.1.2.3377.10.1.1.1.1"),new OctetString("SnmpTrap")));pdu.setType(PDU.TRAP);sendPDU(pdu);System.out.println("Trap sent successfully.");}?
這里PDU的OID和Value可以自己構造,無需使用特定的值。
然后修改地址
targetAddress?= GenericAddress.parse("udp:192.168.1.2/162");
transport?=?new?DefaultUdpTransportMapping(new?UdpAddress("192.168.1.1/161"));
?
另外需要修改target的version,即改為target.setVersion(SnmpConstants.version2c)為什么要這樣改我也沒搞清楚,總之verion1收不到。
接下來修改main()函數,調用setTrap()。
然后回到本機運行剛才的例子,當控制臺顯示“Waiting for traps..”時,運行Agent端的例子。此時如果192.168.1.2打出我們剛剛設置的PDU的信息,就說明Trap的收發成功了。
?
?
總結
以上是生活随笔為你收集整理的使用snmp4j实现Snmp功能(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用snmp4j实现Snmp功能(一)
- 下一篇: 使用snmp4j实现Snmp功能(三)