Android implements the snmp protocol (1) and android implements the snmp protocol

Source: Internet
Author: User
Tags i18n sendmsg

Android implements the snmp protocol (1) and android implements the snmp protocol
Early January 2015. I received a call from a  instructor and asked me to help me develop an App they would use at the Beijing Exhibition, this App can display the running status of  network devices and set some simple parameters, including AP, LSW, AP and AR.
The instructor told me that they managed the protocol using the snmp protocol v2c, which means that I had to implement the Protocol on Android devices and interact with their network devices.
Go back and study it carefully and ask some friends who are familiar with it. Finally, I have a rough understanding of snmp.

Snmp refers to a simple network device management protocol. as its name implies, it is a general standard protocol for managing network devices. It belongs to the TCP/IP application layer. The snmp server occupies port 161, the client uses 162 (based on UDP ).
To enable the snmp protocol on windows, refer to http://blog.csdn.net/zougangx/article/details/6977936. Note that the Security tab of the SNMP Service attribute allows us to Accept snmp Packets from any host for debugging.

The OID (object identifier) is used as the query content for the connection between two devices. For details about the OID content, see http://www.cnblogs.com/aspx-net/p/3554044.html. Some of the OID protocols are well defined, and some device vendors can define it themselves.
After completing the above steps and familiarizing myself with the basic OID commands, some online users say they can use Paessler SNMP Tester for debugging. However, I did not perform this smoothly in actual operations, paessler SNMP Tester always displays noresponse and uses snmputil instead. (Paessler SNMP Tester and snmputil are both tools for testing the snmp protocol on windows, Paessler SNMP Tester has a graphical interface, snmputil is not, the operation of snmputil can refer to the http://blog.chinaunix.net/uid-21857285-id-3340217.html)
When using snmputil, the error on SnmpMgrRequest 40 occurs. refer to the following URL to solve the problem. So far, my snmputil and Paessler SNMP Tester are running normally!
In the service list of the computer, you can see:

The Trap message must be manually enabled, while the service is automatically enabled. As for how to use the snmp trap service, I am not very clear about the reasons for setting the trap tab of the snmp service. I also hope that some people will not be able to give me any further instructions, and I will not conduct any further research on the project.
When both services are enabled, you can use netstat-an | findstr "162" or netstat-an | findstr "161" to check whether the port is developed, 161 you can perform a local test after enabling the tool.


The snmp protocol is a TCP/IP protocol and is completed in c language. I have previously transplanted uip1.0 and it is also written in c language. Android must be implemented using Java. To this end, I first used the snmp4j jar package, established a Java project, and counterfeited examples of official documents, coding is as follows (two jar packages of snmp4j need to be introduced ):

class SnmpManager {

     private TransportMapping transportMapping = null;
     private Snmp snmp = null;
     private int version;

     public final static int version1 = SnmpConstants. version1;
     public final static int version2c = SnmpConstants.version2c;
     public final static int version3 = SnmpConstants. version3;

     / **
      * Construction method
      * @param version
      * /
     public SnmpManager (int version) {
            this. version = version;
            try {
                 // Set to Udp protocol
                 transportMapping = new DefaultUdpTransportMapping ();
                 snmp = new Snmp (transportMapping);

                 if (version == version3) {
                      // Set security information
                     USM usm = new USM (SecurityProtocols.getInstance (), new OctetString (MPv3.createLocalEngineID ()), 0);
                     SecurityModels. GetInstance (). AddSecurityModel (usm);
                }
                 transportMapping.listen ();
           } catch (Exception e) {
                e.printStackTrace ();
                System. Out.println (e);
           }
     }

     / **
      * @param sync
      * @param bro
      * @param pdu
      * @param addr
      * Send message method
      * /
     public void sendMsg (boolean sync, final boolean bro, PDU pdu, String addr) {
           Address targetAddres = GenericAddress. Parse (addr);
           Target target = null;
            if (this. version == version3) {
                 snmp.getUSM (). addUser (new OctetString ("MD5DES"), new UsmUser (new OctetString ("MD5DES"), AuthMD5. ID, new OctetString ("MD5DESUserAuthPassword"), PrivDES.ID, new OctetString ("MD5DESUserPrivPassword") ));
                target = new UserTarget ();
                 // Set the security level
                target.setSecurityLevel (SecurityLevel. AUTH_PRIV);
                target.setSecurityName (new OctetString ("MD5DES"));
                target.setVersion (SnmpConstants. version3);
           } else {
                target = new CommunityTarget ();
                 if (this. version == version1) {
                     target.setVersion (version1);
                     ((CommunityTarget) target) .setCommunity (new OctetString ("public"));
                } else {
                     target.setVersion (version2c);
                     ((CommunityTarget) target) .setCommunity (new OctetString ("public"));
                }
           }

           target.setAddress (targetAddres);
           target.setRetries (2);
           target.setTimeout (1000);

            if (sync) {
                 // send message and accept response
                ResponseEvent response = null;
                 try {
                     response = snmp.send (pdu, target);
                } catch (IOException e) {
                      // TODO Auto-generated catch block
                     e.printStackTrace ();
                     System. Out.println (e);
                }
                 // handle the response
                System. Out.println ("Synchronize message from" + response.getPeerAddress () + "/ nrequest:" + response.getRequest () + "/ nresponse:" + response.getResponse ());
                
           } else {
                ResponseListener listener = new ResponseListener () {
                      @Override
                      public void onResponse (ResponseEvent event) {
                            if (! bro) {
                                ((Snmp) event.getSource ()). Cancel (event.getRequest (), this);
                           }
                            // handle the response
                           PDU request = event.getRequest ();
                           PDU response = event.getResponse ();
                           System. Out.println ("Asynchronise message from" + event.getPeerAddress () + "/ nrequest:" + request + "/ nresponse:" + response);
                     }
                };
                 try {
                      snmp.send (pdu, target, null, listener);
                } catch (IOException e) {
                     e.printStackTrace ();
                     System. Out.println (e);
                }
           }
     }
}

public class SnmpTest {

     public static String myVersion = "";
     static boolean sync = false;
     static boolean bro = false;

     / **
      * Main function
      * @param args
      * /
     public static void main (String [] args) {

           SnmpManager manager = new SnmpManager (SnmpConstants.version2c);
            // construct message
           PDU pdu = new PDU ();
            // PDU pdu = new ScopedPDU (); version3 use
            // Set the object ID to be obtained
           OID oids = new OID ("1.3.6.1.2.1.1.1.0");
// OID oids = new OID (new int [] {1, 3, 6, 1, 2, 1, 1, 1, 0});
           pdu.add (new VariableBinding (oids));
            // Set the message type
           pdu.setType (PDU. GET);
// ((ScopedPDU) pdu) .setContextName (new OctetString ("priv"));
            // Send message, the last one is the target address you want to send
           manager.sendMsg (true, true, pdu, "udp: 127.0.0.1/161");
           
     }
}


The running result is as follows:

It does not work when I port this Java code to the Android project. I have seen some websites such as Baidu, google, and stackoverflow. A friend on stackoverflow also encountered the same problem as me. Someone replied that snmp4j could not be used on Android. Why, I can't explain it to anyone. I need more powerful people!
Because it is a project of a instructor, I can't keep searching for related information like this. I think someone should have made an Android version similar to snmp4j, and I am very sorry. Bytes.

private void buttonFun () {
noNull ();
The
new Thread (new Runnable () {
@Override
public void run () {
// TODO Auto-generated method stub
api = new SnmpAPI ();
session = new SnmpSession (api);

SnmpPDU pdu = new SnmpPDU ();

UDPProtocolOptions protocol = new UDPProtocolOptions ();
protocol.setRemoteHost (getText (target));
protocol.setRemotePort (Integer.parseInt (getText (port)));
pdu.setProtocolOptions (protocol);

// Build Get request PDU
pdu.setCommand (SnmpAPI.GET_REQ_MSG);
pdu.setCommunity (getText (community));
The
if (version.getSelectedItemPosition () == 0) {
pdu.setVersion (SnmpAPI.SNMP_VERSION_1);
The
} else if (version.getSelectedItemPosition () == 1) {
pdu.setVersion (SnmpAPI.SNMP_VERSION_2C);
The
} else if (version.getSelectedItemPosition () == 2) {
// You need to set MD5 SHA authentication password, etc.
pdu.setVersion (SnmpAPI.SNMP_VERSION_3);
}
The

pdu.setTimeout (Integer.parseInt (getText (timeout)));
pdu.setRetries (Integer.parseInt (getText (retries)));

// SnmpOID oid = new SnmpOID ("1.3.6.1.2.1.1.1.0");
// SnmpOID oid = new SnmpOID ((SnmpOID) (getText (oid)));
// pdu.addNull (oid);
The
String oidstr = getText (oid);
String str [] = oidstr.split ("\\.");
int a [] = new int [9];
for (int i = 0; i <str.length; i ++) {
a [i] = Integer.parseInt (str [i]);
}
The
// int a [] = {1, 3, 6, 1, 2, 1, 1, 1, 0};
SnmpOID oid = new SnmpOID (a);
pdu.addNull (oid);

SnmpPDU resp = null;
try {
session.open ();
resp = session.syncSend (pdu);
} catch (SnmpException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
System.out.println (e);
}

if (resp! = null) {
// return varBinds string
UDPProtocolOptions options = (UDPProtocolOptions) resp.getProtocolOptions ();
String resultString = "Response PDU received from" + options.getRemoteAddress () + ". \ N"; // No I18N
resultString = resultString + "Community =" + resp.getCommunity () + ". \ n \ n"; // No I18N
if (resp.getErrstat () == 0) {
resultString = resultString + "VARBINDS: \ n \ n"; // No I18N
resultString = resultString + resp.printVarBinds ();
} else {
// Check for error in response
resultString = resultString + resp.getError ();
}
The
Message msg = new Message ();
msg.what = 1000;
msg.obj = resultString;
myHandler.sendMessage (msg);
The
if (session! = null) {
session.close ();
}
if (api! = null) {
api.close ();
}

} else {
String errorString = "Request timed out to:" + getText (target); // No I18N
Message msg = new Message ();
msg.what = 1000;
msg.obj = errorString;
myHandler.sendMessage (msg);
The
if (session! = null) {
session.close ();
}
if (api! = null) {
api.close ();
}
}
}
}). start ();
} 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.