Last modified by Frank Fock on 2024/05/25 20:55

Show last authors
1 To send a broadcast SNMP message to a target, simply
2
3 1. use a broadcast address as target
4 1. use SNMP v1, v2c, or v3 with noAuthNoPriv security level (broadcast with authentication does not work obviously)
5 1. use the asynchronous response processing model of SNMP4J
6
7 For example:
8
9 ===== Setup a Snmp instance and let it listen to responses =====
10
11 {{code language="java"}}
12 TransportMapping transport = new DefaultUdpTransportMapping();
13 Session snmp = new Snmp(transport);
14 USM usm = new USM(SecurityProtocols.getInstance(),
15 new OctetString(MPv3.createLocalEngineID()), 0);
16 SecurityModels.getInstance().addSecurityModel(usm);
17 snmp.listen();
18 {{/code}}
19
20 ===== Create a broadcast target =====
21
22 {{code language="java"}}
23 Address targetAddress = GenericAddress.parse("udp:255.255.255.255/161");
24 {{/code}}
25
26 * SNMP v1(((
27 {{code language="java"}}
28 CommunityTarget target = new CommunityTarget();
29 target.setCommunity(new OctetString("public"));
30 target.setAddress(targetAddress);
31 target.setRetries(1);
32 target.setTimeout(5000);
33 target.setVersion(SnmpConstants.version1);
34 {{/code}}
35 )))
36
37 * SNMP v2c(((
38 {{code language="java"}}
39 CommunityTarget target = new CommunityTarget();
40 target.setCommunity(new OctetString("public"));
41 target.setAddress(targetAddress);
42 target.setRetries(1);
43 target.setTimeout(5000);
44 target.setVersion(SnmpConstants.version2c);
45 {{/code}}
46 )))
47
48 * SNMPv3(((
49 {{code language="java"}}
50 UserTarget target = new UserTarget();
51 target.setAddress(targetAddress);
52 target.setRetries(1);
53 target.setTimeout(5000);
54 target.setVersion(SnmpConstants.version3);
55 target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
56 target.setSecurityName(new OctetString("unsecUser"));
57 {{/code}}
58 )))
59
60 ===== Create the PDU =====
61
62 {{code language="java"}}
63 PDU pdu = new PDU();
64 pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,1})));
65 pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,2})));
66 pdu.setType(PDU.GETNEXT);
67 {{/code}}
68
69 ===== Send the message asynchronously =====
70
71 {{code language="java"}}
72 class MyResponseListener implements ResponseListener {
73 boolean finished = false;
74 public void onResponse(ResponseEvent event) {
75 System.out.println("Received response PDU is: "+event.getResponse());
76 if (event.getResponse() == null) {
77 finished = true;
78 listener.notify();
79 }
80 }
81
82 public boolean isFinished() {
83 return finished;
84 }
85 };
86
87 MyResponseListener listener = new MyResponseListener() {
88 snmp.sendPDU(pdu, target, null, listener);
89 try {
90 while (!listener.isFinished()) {
91 listener.wait(target.getTimeout()*2);
92 }
93 } catch (InterruptedException iex) {
94 System.out.println("Request cancelled: "+iex.getMessage());
95 }
96 {{/code}}