- All Implemented Interfaces:
Closeable,AutoCloseable,EventListener,CommandResponder,Session
Snmp class is the core of SNMP4J. It provides functions to send and receive SNMP PDUs. All SNMP PDU types
can be send. Confirmed PDUs can be sent synchronously and asynchronously.
The Snmp class is transport protocol independent. Support for a specific TransportMapping instance is
added by calling the addTransportMapping(TransportMapping transportMapping) method or creating a
Snmp instance by using the non-default constructor with the corresponding transport mapping. Transport mappings are
used for incoming and outgoing messages.
To setup a default SNMP session for UDP transport and with SNMPv3 support the following code snippet can be used:
Address targetAddress = GenericAddress.parse("udp:127.0.0.1/161");
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(),
new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
How a synchronous SNMPv3 message with authentication and privacy is then sent illustrates the following code snippet:
// add user to the USM
snmp.getUSM().addUser(new OctetString("MD5DES"),
new UsmUser(new OctetString("MD5DES"),
AuthMD5.ID,
new OctetString("MD5DESUserAuthPassword"),
PrivDES.ID,
new OctetString("MD5DESUserPrivPassword")));
// create the target
UserTarget target = new UserTarget();
target.setAddress(targetAddress);
target.setRetries(1);
target.setTimeout(5000);
target.setVersion(SnmpConstants.version3);
target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
target.setSecurityName(new OctetString("MD5DES"));
// create the PDU
PDU pdu = new ScopedPDU();
pdu.add(new VariableBinding(new OID("1.3.6")));
pdu.setType(PDU.GETNEXT);
// send the PDU
ResponseEvent response = snmp.send(pdu, target);
// extract the response PDU (could be null if timed out)
PDU responsePDU = response.getResponse();
// extract the address used by the agent to send the response:
Address peerAddress = response.getPeerAddress();
An asynchronous SNMPv1 request is sent by the following code:
// setting up target
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version1);
// creating PDU
PDU pdu = new PDU();
pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,1})));
pdu.add(new VariableBinding(new OID(new int[] {1,3,6,1,2,1,1,2})));
pdu.setType(PDU.GETNEXT);
// sending request
ResponseListener listener = new ResponseListener() {
public void onResponse(ResponseEvent event) {
// Always cancel async request when response has been received
// otherwise a memory leak is created! Not canceling a request
// immediately can be useful when sending a request to a broadcast
// address.
((Snmp)event.getSource()).cancel(event.getRequest(), this);
System.out.println("Received response PDU is: "+event.getResponse());
}
};
snmp.sendPDU(pdu, target, null, listener);
Traps (notifications) and other SNMP PDUs can be received by adding the following code to the first code snippet above:
CommandResponder trapPrinter = new CommandResponder() {
public synchronized void processPdu(CommandResponderEvent e) {
PDU command = e.getPDU();
if (command != null) {
System.out.println(command.toString());
}
}
};
snmp.addCommandResponder(trapPrinter);
- Version:
- 3.7.5
- Author:
- Frank Fock
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionclassTheNotificationDispatcherdispatches traps, notifications, and to registered listeners.protected classSnmp.PendingRequest<A extends Address>static interfaceInterface for handling reports. -
Constructor Summary
ConstructorsConstructorDescriptionSnmp()Creates aSnmpinstance that uses aMessageDispatcherImplwith no message processing models and no security protocols (by default).Snmp(MessageDispatcher messageDispatcher) Creates aSnmpinstance by supplying aMessageDispatcher.Snmp(MessageDispatcher messageDispatcher, TransportMapping<? extends Address> transportMapping) Creates aSnmpinstance by supplying aMessageDispatcherand aTransportMapping.Snmp(TransportMapping<? extends Address> transportMapping) Creates aSnmpinstance that uses aMessageDispatcherImplwith all supported message processing models and the default security protocols for dispatching. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddCommandResponder(CommandResponder listener) Adds aCommandResponderto this SNMP session.booleanaddNotificationListener(Address listenAddress, CommandResponder listener) Adds a notification listener to this Snmp instance.booleanaddNotificationListener(TransportMapping<?> transportMapping, Address listenAddress, CommandResponder listener) Adds a notification listener to this Snmp instance.voidaddTransportMapping(TransportMapping<? extends Address> transportMapping) Adds aTransportMappingto this SNMP session.voidcancel(PDU request, ResponseListener listener) Cancels an asynchronous request.voidclose()Closes the session and frees any allocated resources, i.e.protected voidcreateLocalizedUsmUserEntry(byte[] engineID, OctetString securityName, OID authProtocol, OctetString authPassword, OID privProtocol, OctetString privPassword) Create and return aUsmUserEntrywith localized authentication and privacy keys from the provided authentication and privacy passwords.protected Snmp.NotificationDispatcherCreates the internalSnmp.NotificationDispatcherused to dispatch notifications.<A extends Address>
byte[]discoverAuthoritativeEngineID(A address, long timeout) Discovers the engine ID of the SNMPv3 entity denoted by the supplied address.protected voidfireProcessPdu(CommandResponderEvent<?> event) Fires aCommandResponderEventevent to inform listeners about a received PDU.<A extends Address>
ResponseEvent<A> Sends a GET request to a target.<A extends Address>
voidget(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) Asynchronously sends a GET requestPDUto the given target.<A extends Address>
ResponseEvent<A> Sends a GETBULK request to a target.<A extends Address>
voidgetBulk(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) Asynchronously sends a GETBULK requestPDUto the given target.getCachedContextEngineId(Address targetAddress) Get a cached RFC 5343 context engine ID for the specified address.Gets the counter support for Snmp related counters.byte[]Gets the local engine ID if the MPv3 is available, otherwise a runtime exception is thrown.Returns the message dispatcher associated with this SNMP session.getMessageProcessingModel(int messageProcessingModel) Gets the message processing model for the supplied ID.<A extends Address>
ResponseEvent<A> Sends a GETNEXT request to a target.<A extends Address>
voidgetNext(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) Asynchronously sends a GETNEXT requestPDUto the given target.intGets the next unique request ID.getNotificationListenerTM(Address listenAddress) Gets the transport mapping registered for the specified listen address.intGets the number of currently pending asynchronous requests.intGets the number of currently pending synchronous requests.Returns the report handler which is used internally to process reports received from command responders.Gets theResponseEventfactory currently used.Gets the timeout model associated with this SNMP session.getUSM()Gets the User Based Security Model (USM).protected voidhandleInternalResponse(PDU response, PDU pdu, Address target) <A extends Address>
ResponseEvent<A> Sends an INFORM request to a target.<A extends Address>
voidinform(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) Asynchronously sends an INFORM requestPDUto the given target.protected final voidbooleanChecks whether RFC5343 based context engine ID discovery is disabled or not.voidlisten()Puts all associated transport mappings into listen mode.protected <A extends Address>
TransportMapping<? super A> lookupTransportMapping(Target<A> target) voidSends a SNMPv2c or SNMPv3 notification to a target.<A extends Address>
voidprocessPdu(CommandResponderEvent<A> event) Process an incoming request or notification PDU.removeCachedContextEngineId(Address target) Remove a cached RFC 5343 context engine ID for the specified address and return it.voidremoveCommandResponder(CommandResponder listener) Removes aCommandResponderfrom this SNMP session.booleanremoveNotificationListener(Address listenAddress) Removes (deletes) the notification listener for the specified transport endpoint.voidremoveTransportMapping(TransportMapping<? extends Address> transportMapping) Removes the specified transport mapping from this SNMP session.protected <A extends Address>
booleanresendRequest(Snmp.PendingRequest<A> request, PDU response) <A extends Address>
ResponseEvent<A> Sends aPDUto the given target and returns the received responsePDU.<A extends Address>
voidsend(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) Asynchronously sends aPDUto the given target.<A extends Address>
ResponseEvent<A> send(PDU pdu, Target<A> target, TransportMapping<? super A> transport) Sends aPDUto the given target and if thePDUis a confirmed request, then the received response is returned synchronously.<A extends Address>
voidsend(PDU pdu, Target<A> target, TransportMapping<? super A> transport, Object userHandle, ResponseListener listener) Asynchronously sends aPDUto the given target.sendMessage(PDU pdu, Target<A> target, TransportMapping<? super A> transport, PduHandleCallback<PDU> pduHandleCallback) Actually sends a PDU to a target and returns a handle for the sent PDU.voidset(PDU pdu, Target<?> target, Object userHandle, ResponseListener listener) Asynchronously sends a SET requestPDUto the given target.<A extends Address>
ResponseEvent<A> Sends a SET request to a target.voidsetContextEngineIdDiscoveryDisabled(boolean contextEngineIdDiscoveryDisabled) Sets the RFC5343 based context engine ID discovery.voidsetCounterSupport(CounterSupport counterSupport) Sets the counter support instance to handle counter events on behalf of this Snmp instance.voidsetLocalEngine(byte[] engineID, int engineBoots, int engineTime) Sets the local engine ID for the SNMP entity represented by thisSnmpinstance.setLocalizedUserCredentials(DirectUserTarget<?> directUserTarget, UsmUserEntry localizedUserCredentials) Sets the user's security name and authentication/privacy keys and protocols on the suppliedDirectUserTargetand returns the maximumSecurityLevelit can be used with.voidsetMessageDispatcher(MessageDispatcher messageDispatcher) Sets the message dispatcher associated with this SNMP session.voidsetReportHandler(Snmp.ReportHandler reportHandler) Sets the report handler and overrides the default report handler.voidsetResponseEventFactory(ResponseEventFactory responseEventFactory) Sets theResponseEventFactoryused to create theResponseEventthat describes the result of a processed or timed out request.voidsetTimeoutModel(TimeoutModel timeoutModel) Sets the timeout model for this SNMP session.voidSends a SNMPv1 trap to a target.
-
Constructor Details
-
Snmp
public Snmp()Creates aSnmpinstance that uses aMessageDispatcherImplwith no message processing models and no security protocols (by default). You will have to add those by calling the appropriate methods ongetMessageDispatcher().At least one transport mapping has to be added before
listen()is called in order to be able to send and receive SNMP messages.To initialize a
Snmpinstance created with this constructor follow this sample code:Transport transport = ...; Snmp snmp = new Snmp(); SecurityProtocols.getInstance().addDefaultProtocols(); MessageDispatcher disp = snmp.getMessageDispatcher(); disp.addMessageProcessingModel(new MPv1()); disp.addMessageProcessingModel(new MPv2c()); snmp.addTransportMapping(transport); OctetString localEngineID = new OctetString( MPv3.createLocalEngineID()); // For command generators, you may use the following code to avoid // engine ID clashes: // MPv3.createLocalEngineID( // new OctetString("MyUniqueID"+System.currentTimeMillis()))); USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0); disp.addMessageProcessingModel(new MPv3(usm)); snmp.listen(); -
Snmp
Creates aSnmpinstance that uses aMessageDispatcherImplwith all supported message processing models and the default security protocols for dispatching.To initialize a
Snmpinstance created with this constructor follow this sample code:Transport transport = ...; Snmp snmp = new Snmp(transport); OctetString localEngineID = new OctetString(snmp.getMPv3().getLocalEngineID()); USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0); SecurityModels.getInstance().addSecurityModel(usm); snmp.listen();
- Parameters:
transportMapping- TransportMapping the initialTransportMapping. You can add more or remove the same later.
-
Snmp
public Snmp(MessageDispatcher messageDispatcher, TransportMapping<? extends Address> transportMapping) Creates aSnmpinstance by supplying aMessageDispatcherand aTransportMapping.As of version 1.1, the supplied message dispatcher is not altered in terms of adding any message processing models to it. This has to be done now outside the Snmp class.
To initialize a
Snmpinstance created with this constructor follow this sample code:Transport transport = ...; SecurityProtocols.getInstance().addDefaultProtocols(); MessageDispatcher disp = new MessageDispatcherImpl(); disp.addMessageProcessingModel(new MPv1()); disp.addMessageProcessingModel(new MPv2c()); Snmp snmp = new Snmp(disp, transport); OctetString localEngineID = new OctetString( MPv3.createLocalEngineID()); // For command generators, you may use the following code to avoid // engine ID clashes: // MPv3.createLocalEngineID( // new OctetString("MyUniqueID"+System.currentTimeMillis()))); USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0); disp.addMessageProcessingModel(new MPv3(usm)); snmp.listen();- Parameters:
messageDispatcher- aMessageDispatcherinstance that will be used to dispatch incoming and outgoing messages.transportMapping- the initialTransportMapping, which may benull. You can add or remove transport mappings later usingaddTransportMapping(org.snmp4j.TransportMapping<? extends org.snmp4j.smi.Address>)andremoveTransportMapping(org.snmp4j.TransportMapping<? extends org.snmp4j.smi.Address>)respectively.
-
Snmp
Creates aSnmpinstance by supplying aMessageDispatcher.The supplied message dispatcher is not altered in terms of adding any message processing models to it. This has to be done now outside the Snmp class.
Do not forget to add at least one transport mapping before calling the listen method!
To initialize a
Snmpinstance created with this constructor follow this sample code:Transport transport = ...; SecurityProtocols.getInstance().addDefaultProtocols(); MessageDispatcher disp = new MessageDispatcherImpl(); disp.addMessageProcessingModel(new MPv1()); disp.addMessageProcessingModel(new MPv2c()); Snmp snmp = new Snmp(disp); snmp.addTransportMapping(transport); OctetString localEngineID = new OctetString( MPv3.createLocalEngineID()); // For command generators, you may use the following code to avoid // engine ID clashes: // MPv3.createLocalEngineID( // new OctetString("MyUniqueID"+System.currentTimeMillis()))); USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0); disp.addMessageProcessingModel(new MPv3(usm)); snmp.listen();- Parameters:
messageDispatcher- aMessageDispatcherinstance that will be used to dispatch incoming and outgoing messages.- Since:
- 1.5
-
-
Method Details
-
initMessageDispatcher
protected final void initMessageDispatcher() -
getMessageDispatcher
Returns the message dispatcher associated with this SNMP session.- Returns:
- a
MessageDispatcherinstance. - Since:
- 1.1
-
setMessageDispatcher
Sets the message dispatcher associated with this SNMP session. TheCommandResponderregistration is removed from the existing message dispatcher (if notnull).- Parameters:
messageDispatcher- a message dispatcher that processes incoming SNMPPDUs.- Since:
- 2.5.7
-
addTransportMapping
Adds aTransportMappingto this SNMP session.- Parameters:
transportMapping- aTransportMappinginstance.
-
removeTransportMapping
Removes the specified transport mapping from this SNMP session. If the transport mapping is not currently part of this SNMP session, this method will have no effect.- Parameters:
transportMapping- a previously addedTransportMapping.
-
addNotificationListener
public boolean addNotificationListener(TransportMapping<?> transportMapping, Address listenAddress, CommandResponder listener) Adds a notification listener to this Snmp instance. Calling this method will create a transport mapping for the specified listening address and registers the providedCommandResponderwith the internalNotificationDispatcher.- Parameters:
transportMapping- the TransportMapping that is listening on the provided listenAddress. CallTransportMappings.getInstance().createTransportMapping(listenAddress);to create such a transport mapping.listenAddress- theAddressdenoting the transport end-point (interface and port) to listen for incoming notifications.listener- theCommandResponderinstance that should handle the received notifications.- Returns:
trueif registration was successful andfalseif, for example, the transport mapping for the listen address could not be created.- Since:
- 2.5.0
-
createNotificationDispatcher
Creates the internalSnmp.NotificationDispatcherused to dispatch notifications.- Returns:
- a new notification dispatcher instance derived from the
Snmp.NotificationDispatcherclass. - Since:
- 3.4.2
-
addNotificationListener
Adds a notification listener to this Snmp instance. Calling this method will create a transport mapping for the specified listening address and registers the providedCommandResponderwith the internalNotificationDispatcher.- Parameters:
listenAddress- theAddressdenoting the transport end-point (interface and port) to listen for incoming notifications.listener- theCommandResponderinstance that should handle the received notifications.- Returns:
trueif registration was successful andfalseif, for example, the transport mapping for the listen address could not be created.- Since:
- 1.6
-
removeNotificationListener
Removes (deletes) the notification listener for the specified transport endpoint.- Parameters:
listenAddress- the listenAddressto be removed.- Returns:
trueif the notification listener has been removed successfully.
-
getNotificationListenerTM
Gets the transport mapping registered for the specified listen address.- Parameters:
listenAddress- the listen address.- Returns:
- the
TransportMappingfor the specified listen address ornullif there is no notification listener for that address. - Since:
- 2.5.0
-
listen
Puts all associated transport mappings into listen mode.- Throws:
IOException- if a transport mapping throws anIOExceptionwhen itsTransportMapping.listen()method has been called.
-
getNextRequestID
public int getNextRequestID()Gets the next unique request ID. The returned ID is unique across the last 2^31-1 IDs generated by this message dispatcher.- Returns:
- an integer value in the range 1..2^31-1. The returned ID can be used to map responses to requests send through this message dispatcher.
- Since:
- 1.1
- See Also:
-
close
Closes the session and frees any allocated resources, i.e. sockets and the internal thread for processing request timeouts. In addition,MessageDispatcher.stop()is called to temrinate and free resources from the used message dispatcher too.If there are any pending requests, the
ResponseListenerassociated with the pending requests, will be called with anullresponse and aInterruptedExceptionin the error member of theResponseEventreturned.After a
Sessionhas been closed it must not be used anymore.- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Specified by:
closein interfaceSession- Throws:
IOException- if a transport mapping cannot be closed successfully.
-
get
Sends a GET request to a target. This method sets the PDU's type toPDU.GETand then sends a synchronous request to the supplied target.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- aPDUinstance. For SNMPv3 messages, the supplied PDU instance has to be aScopedPDUinstance.target- the Target instance representing the target SNMP engine where to send thepdu.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. - Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
get
public <A extends Address> void get(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) throws IOException Asynchronously sends a GET requestPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.userHandle- an user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
getNext
Sends a GETNEXT request to a target. This method sets the PDU's type toPDU.GETNEXTand then sends a synchronous request to the supplied target. This method is a convenience wrapper for thesend(PDU pdu, Target target)method.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- aPDUinstance. For SNMPv3 messages, the supplied PDU instance has to be aScopedPDUinstance.target- the Target instance representing the target SNMP engine where to send thepdu.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. - Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
getNext
public <A extends Address> void getNext(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) throws IOException Asynchronously sends a GETNEXT requestPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.userHandle- a user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
getBulk
Sends a GETBULK request to a target. This method sets the PDU's type toPDU.GETBULKand then sends a synchronous request to the supplied target. This method is a convenience wrapper for thesend(PDU pdu, Target target)method.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- aPDUinstance. For SNMPv3 messages, the supplied PDU instance has to be aScopedPDUinstance.target- the Target instance representing the target SNMP engine where to send thepdu.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. - Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
getBulk
public <A extends Address> void getBulk(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) throws IOException Asynchronously sends a GETBULK requestPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.userHandle- a user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
inform
Sends an INFORM request to a target. This method sets the PDU's type toPDU.INFORMand then sends a synchronous request to the supplied target. This method is a convenience wrapper for thesend(PDU pdu, Target target)method.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- aPDUinstance. For SNMPv3 messages, the supplied PDU instance has to be aScopedPDUinstance.target- the Target instance representing the target SNMP engine where to send thepdu.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. - Throws:
IOException- if the inform request could not be send to the specified target.- Since:
- 1.1
-
inform
public <A extends Address> void inform(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) throws IOException Asynchronously sends an INFORM requestPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.userHandle- a user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
trap
Sends a SNMPv1 trap to a target. This method sets the PDU's type toPDU.V1TRAPand then sends it to the supplied target. This method is a convenience wrapper for thesend(PDU pdu, Target target)method.- Parameters:
pdu- aPDUv1instance.target- the Target instance representing the target SNMP engine where to send thepdu. The selected SNMP protocol version for the target must beSnmpConstants.version1.- Throws:
IOException- if the trap cannot be sent.- Since:
- 1.1
-
notify
Sends a SNMPv2c or SNMPv3 notification to a target. This method sets the PDU's type toPDU.NOTIFICATIONand then sends it to the supplied target. This method is a convenience wrapper for thesend(PDU pdu, Target target)method.- Parameters:
pdu- aPDUv1instance.target- the Target instance representing the target SNMP engine where to send thepdu. The selected SNMP protocol version for the target must beSnmpConstants.version2corSnmpConstants.version2c.- Throws:
IOException- if the notification cannot be sent.- Since:
- 1.1
-
set
Sends a SET request to a target. This method sets the PDU's type toPDU.SETand then sends a synchronous request to the supplied target.- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- aPDUinstance. For SNMPv3 messages, the supplied PDU instance has to be aScopedPDUinstance.target- the Target instance representing the target SNMP engine where to send thepdu.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. - Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
set
public void set(PDU pdu, Target<?> target, Object userHandle, ResponseListener listener) throws IOException Asynchronously sends a SET requestPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.userHandle- an user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the PDU cannot be sent to the target.- Since:
- 1.1
-
send
Description copied from interface:SessionSends aPDUto the given target and returns the received responsePDU.- Specified by:
sendin interfaceSession- Type Parameters:
A- theAddresstype of target and response (i.e., must be the same)- Parameters:
pdu- thePDUto send.target- theTargetinstance that specifies how and where to send the PDU.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. If the sentpduis an unconfirmed PDU (notification, response, or report), thennullwill be returned. - Throws:
IOException- if the message could not be send.
-
send
public <A extends Address> ResponseEvent<A> send(PDU pdu, Target<A> target, TransportMapping<? super A> transport) throws IOException Sends aPDUto the given target and if thePDUis a confirmed request, then the received response is returned synchronously.- Specified by:
sendin interfaceSession- Type Parameters:
A- type of the targetAddress- Parameters:
pdu- aPDUinstance. When sending a SNMPv1 trap PDU, the supplied PDU instance must be aPDUv1. For all types of SNMPv3 messages, the supplied PDU instance has to be aScopedPDUinstance.target- the Target instance representing the target SNMP engine where to send thepdu.transport- specifies theTransportMappingto be used when sending the PDU. Iftransportisnull, the associated message dispatcher will try to determine the transport mapping by thetarget's address.- Returns:
- the received response encapsulated in a
ResponseEventinstance. To obtain the received responsePDUcallResponseEvent.getResponse(). If the request timed out, that method will returnnull. If the sentpduis an unconfirmed PDU (notification, response, or report), thennullwill be returned. - Throws:
IOException- if the message could not be sent.- See Also:
-
send
public <A extends Address> void send(PDU pdu, Target<A> target, Object userHandle, ResponseListener listener) throws IOException Description copied from interface:SessionAsynchronously sends aPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Specified by:
sendin interfaceSession- Type Parameters:
A- theAddresstype of target and response (i.e., must be the same)- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.userHandle- an user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the message could not be send.
-
send
public <A extends Address> void send(PDU pdu, Target<A> target, TransportMapping<? super A> transport, Object userHandle, ResponseListener listener) throws IOException Description copied from interface:SessionAsynchronously sends aPDUto the given target. The response is then returned by calling the suppliedResponseListenerinstance.- Specified by:
sendin interfaceSession- Type Parameters:
A- the targetAddresstype.- Parameters:
pdu- the PDU instance to send.target- the Target instance representing the target SNMP engine where to send thepdu.transport- specifies theTransportMappingto be used when sending the PDU. Iftransportisnull, the associated message dispatcher will try to determine the transport mapping by thetarget's address.userHandle- an user defined handle that is returned when the request is returned via thelistenerobject.listener- aResponseListenerinstance that is called whenpduis a confirmed PDU and the request is either answered or timed out.- Throws:
IOException- if the message could not be send.
-
sendMessage
protected <A extends Address> PduHandle sendMessage(PDU pdu, Target<A> target, TransportMapping<? super A> transport, PduHandleCallback<PDU> pduHandleCallback) throws IOException Actually sends a PDU to a target and returns a handle for the sent PDU.- Type Parameters:
A- the targetAddresstype.- Parameters:
pdu- thePDUinstance to be sent.target- aTargetinstance denoting the target SNMP entity.transport- the (optional) transport mapping to be used to send the request. Iftransportisnulla suitable transport mapping is determined from thetargetaddress.pduHandleCallback- callback for newly created PDU handles before the request is sent out.- Returns:
- PduHandle that uniquely identifies the sent PDU for further reference.
- Throws:
IOException- if the transport fails to send the PDU or the if the message cannot be BER encoded.
-
lookupTransportMapping
-
cancel
Description copied from interface:SessionCancels an asynchronous request. Any asynchronous request must be canceled when the supplied response listener is being called, even if theResponseEventindicates an error.- Specified by:
cancelin interfaceSession- Parameters:
request- a request PDU as sent viaSession.send(PDU pdu, Target target, Object userHandle, ResponseListener listener)or any .listener- a ResponseListener instance.
-
setLocalEngine
public void setLocalEngine(byte[] engineID, int engineBoots, int engineTime) Sets the local engine ID for the SNMP entity represented by thisSnmpinstance. This is a convenience method that sets the local engine ID in the associatedMPv3andUSM.- Specified by:
setLocalEnginein interfaceSession- Parameters:
engineID- a byte array containing the local engine ID. The length and content has to comply with the constraints defined in the SNMP-FRAMEWORK-MIB.engineBoots- the number of boots of this SNMP engine (zero based).engineTime- the number of seconds since the value of engineBoots last changed.- See Also:
-
getLocalEngineID
public byte[] getLocalEngineID()Gets the local engine ID if the MPv3 is available, otherwise a runtime exception is thrown.- Specified by:
getLocalEngineIDin interfaceSession- Returns:
- byte[] the local engine ID.
-
discoverAuthoritativeEngineID
Discovers the engine ID of the SNMPv3 entity denoted by the supplied address. This method does not need to be called for normal operation, because SNMP4J automatically discovers authoritative engine IDs and also automatically synchronize engine time values. For this method to operate successfully, the discover engine IDs flag inUSMmust betrue(which is the default).- Type Parameters:
A- theAddresstype.- Parameters:
address- an Address instance representing the transport address of the SNMPv3 entity for which its authoritative engine ID should be discovered.timeout- the maximum time in milliseconds to wait for a response.- Returns:
- a byte array containing the authoritative engine ID or
nullif it could not be discovered. - See Also:
-
getUSM
Gets the User Based Security Model (USM). This is a convenience method that uses theMPv3.getSecurityModel(int)method of the associated MPv3 instance to get the USM.- Returns:
- the
USMinstance associated with the MPv3 bound to thisSnmpinstance, ornullotherwise.
-
getMessageProcessingModel
Gets the message processing model for the supplied ID.- Parameters:
messageProcessingModel- a mesage processing model ID as defined inMessageProcessingModel.- Returns:
- MessageProcessingModel a
MessageProcessingModelifmessageProcessingModelhas been registered with the message dispatcher associated with this SNMP session.
-
processPdu
Process an incoming request or notification PDU.- Specified by:
processPduin interfaceCommandResponder- Type Parameters:
A- type of the peerAddress.- Parameters:
event- aCommandResponderEventwith the decoded incoming PDU as dispatched to this method call by the associated message dispatcher.
-
isContextEngineIdDiscoveryDisabled
public boolean isContextEngineIdDiscoveryDisabled()Checks whether RFC5343 based context engine ID discovery is disabled or not. The default value isfalse.- Returns:
trueif context engine ID discovery is disabled.- Since:
- 2.0
-
setContextEngineIdDiscoveryDisabled
public void setContextEngineIdDiscoveryDisabled(boolean contextEngineIdDiscoveryDisabled) Sets the RFC5343 based context engine ID discovery. The default value isfalse.- Parameters:
contextEngineIdDiscoveryDisabled-trueto disable context engine ID discovery and remove all cached context engine IDs from the internal cache,falseto enable context engine ID discovery.- Since:
- 2.0
-
getCachedContextEngineId
Get a cached RFC 5343 context engine ID for the specified address.- Parameters:
targetAddress- the target address that returned the context engine ID.- Returns:
- the cached context engine ID retrieved by RFC 5343 discovery or
nullif no such ID had been cached yet or the cached value was already removed either explicitly withremoveCachedContextEngineId(Address)or implicitly because the address object was no longer associated with any open connection (i.e., the internallyWeakHashMaprecognized no more active references on the address key). - Since:
- 3.6.5
-
removeCachedContextEngineId
Remove a cached RFC 5343 context engine ID for the specified address and return it. To remove all cached IDs, callsetContextEngineIdDiscoveryDisabled(boolean)withtrue.- Parameters:
target- the target address that returned the context engine ID.- Returns:
- the removed cached context engine ID retrieved by RFC 5343 discovery or
nullif no such ID had been cached yet. - Since:
- 3.6.5
-
resendRequest
-
handleInternalResponse
-
removeCommandResponder
Removes aCommandResponderfrom this SNMP session.- Parameters:
listener- a previously addedCommandResponderinstance.
-
addCommandResponder
Adds aCommandResponderto this SNMP session. The command responder will then be informed about incoming SNMP PDUs of any kind that are not related to any outstanding requests of this SNMP session.- Parameters:
listener- theCommandResponderinstance to be added.
-
fireProcessPdu
Fires aCommandResponderEventevent to inform listeners about a received PDU. If a listener has marked the event as processed further listeners will not be informed about the event.- Parameters:
event- aCommandResponderEvent.
-
getTimeoutModel
Gets the timeout model associated with this SNMP session.- Returns:
- a TimeoutModel instance (never
null). - See Also:
-
getReportHandler
Returns the report handler which is used internally to process reports received from command responders.- Returns:
- the
ReportHandlerinstance. - Since:
- 1.6
-
getCounterSupport
Gets the counter support for Snmp related counters. These are for example: snmp4jStatsRequestTimeouts, snmp4jStatsRequestTimeouts, snmp4jStatsRequestWaitTime- Returns:
- the counter support if available. If the
SNMP4JSettings.getSnmp4jStatistics()value isSNMP4JSettings.Snmp4jStatistics.nonethen no counter support will be created and no statistics will be collected. - Since:
- 2.4.2
-
setCounterSupport
Sets the counter support instance to handle counter events on behalf of this Snmp instance.- Parameters:
counterSupport- the counter support instance that collects the statistics events created by this Snmp instance. See alsogetCounterSupport().- Since:
- 2.4.2
-
setTimeoutModel
Sets the timeout model for this SNMP session. The default timeout model sends retries whenever the time specified by thetimeoutparameter of the target has elapsed without a response being received for the request. By specifying a different timeout model this behaviour can be changed.- Parameters:
timeoutModel- aTimeoutModelinstance (must not benull).
-
setReportHandler
Sets the report handler and overrides the default report handler.- Parameters:
reportHandler- aReportHandlerinstance which must not benull.- Since:
- 1.6
-
getPendingSyncRequestCount
public int getPendingSyncRequestCount()Gets the number of currently pending synchronous requests.- Returns:
- the size of the synchronous request queue.
- Since:
- 2.4.2
-
getPendingAsyncRequestCount
public int getPendingAsyncRequestCount()Gets the number of currently pending asynchronous requests.- Returns:
- the size of the asynchronous request queue.
- Since:
- 2.4.2
-
createLocalizedUsmUserEntry
public UsmUserEntry createLocalizedUsmUserEntry(byte[] engineID, OctetString securityName, OID authProtocol, OctetString authPassword, OID privProtocol, OctetString privPassword) Create and return aUsmUserEntrywith localized authentication and privacy keys from the provided authentication and privacy passwords.- Parameters:
engineID- the authoritative engine ID of the target for which the newUsmUserEntryshould be localized.securityName- the (security) user name of the user.authProtocol- the authentication protocol OID. Ifnullis provided, no authentication key and no privacy key will be set in the returned user entry.authPassword- the password which will be localized usingSecurityProtocols.passwordToKey(OID, OctetString, byte[]). Ifnullis provided, no authentication key and no privacy key will be set in the returned user entry.privProtocol- the authentication protocol OID. Ifnullis provided, no authentication key and no privacy key will be set in the returned user entry.privPassword- the password which will be localized usingSecurityProtocols.passwordToKey(OID, OID, OctetString, byte[]). Ifnullis provided, no privacy key will be set in the returned user entry.- Returns:
- the created
UsmUserEntrywith any given passwords localized to the engine ID corresponding keys. - Since:
- 3.4.0
-
setLocalizedUserCredentials
public SecurityLevel setLocalizedUserCredentials(DirectUserTarget<?> directUserTarget, UsmUserEntry localizedUserCredentials) Sets the user's security name and authentication/privacy keys and protocols on the suppliedDirectUserTargetand returns the maximumSecurityLevelit can be used with.- Parameters:
directUserTarget- the direct user target to be modified. Security name is set always and authentication protocol and key only if provided in the givenlocalizedUserCredentialsand if the authentication protocol is available fromgetMPv3()#getAuthenticationProtocol}. The privacy key and protocol are set only if provided the authentication could be set and if the privacy key is set inlocalizedUserCredentialsprotocol is available fromgetMPv3()#getPrivacyProtocol}localizedUserCredentials- aUsmUserEntrypreferably created bycreateLocalizedUsmUserEntry(byte[], OctetString, OID, OctetString, OID, OctetString)that must contain already localized keys (or no keys at all).- Returns:
- the maximum
SecurityLevelthe modifiedDirectUserTargetdirectUserTarget now supports. - Since:
- 3.4.0
-
closeTransportMapping
-
getResponseEventFactory
Gets theResponseEventfactory currently used.- Returns:
- an implementation of the
ResponseEventFactoryinterface. - Since:
- 3.7.5
-
setResponseEventFactory
Sets theResponseEventFactoryused to create theResponseEventthat describes the result of a processed or timed out request.- Parameters:
responseEventFactory- an implementation of theResponseEventFactoryinterface.- Since:
- 3.7.5
-