SNMP代码不适用于TCP

时间:2017-03-21 08:08:11

标签: java tcp snmp

我有一个SNMPV3陷阱的例子,当我使用DefaultUdpTransportMapping它工作正常但是当我使用DefaultTcpTransportMapping时,它将返回null响应事件。

我还附上了以下代码。

public class SnmpUtilSendTrapV3 {

    private Snmp snmp = null;
    private Address targetAddress = null;

    // private TcpAddress targetAddress = null;

    public void initComm() throws IOException {
        targetAddress = new TcpAddress(Inet4Address.getLocalHost(), 162);
        // targetAddress = GenericAddress.parse("127.0.0.1/162");
        TransportMapping transport = new DefaultTcpTransportMapping();
        snmp = new Snmp(transport);

        snmp.listen();

    }

    /**
     * send trap
     *
     * @throws IOException
     */
    public void sendPDU() throws IOException {
        UserTarget target = new UserTarget();
        target.setAddress(targetAddress);
        target.setRetries(2);
        target.setTimeout(1500);
        // snmp version
        target.setVersion(SnmpConstants.version3);

        // target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
        target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
        target.setSecurityName(new OctetString("MD5DES"));

        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
                MPv3.createLocalEngineID()), 0);
        usm.setEngineDiscoveryEnabled(true);
        SecurityModels.getInstance().addSecurityModel(usm);

        UsmUser user = new UsmUser(new OctetString("MD5DES"), AuthMD5.ID,
                new OctetString("MD5DESUserAuthPassword"), PrivDES.ID,
                new OctetString("MD5DESUserPrivPassword"));
        snmp.getUSM().addUser(new OctetString("MD5DES"), user);

        // create PDU
        ScopedPDU pdu = new ScopedPDU();
        pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.3.0"),
                new OctetString("DemoTrapv3")));
        pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.5.0"),
                new OctetString("Demo")));
        pdu.setType(PDU.TRAP);

        // send PDU to Agent and recieve Response
        ResponseEvent respEvnt = snmp.send(pdu, target);

        // analyze Response
        if (respEvnt != null && respEvnt.getResponse() != null) {
            Vector<VariableBinding> variableBindings = (Vector<VariableBinding>) respEvnt
                    .getResponse().getVariableBindings();
            Vector<VariableBinding> recVBs = variableBindings;
            for (int i = 0; i < recVBs.size(); i++) {
                VariableBinding recVB = recVBs.elementAt(i);
                System.out
                        .println(recVB.getOid() + " : " + recVB.getVariable());
            }
        }
        snmp.close();
    }

    public static void main(String[] args) {
        try {
            SnmpUtilSendTrapV3 util = new SnmpUtilSendTrapV3();
            util.initComm();
            util.sendPDU();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



public class MultiThreadedTrapReceiver implements CommandResponder {

    private Address address = GenericAddress.parse("0.0.0.0/162");
    private int numDispatcherThreads = 2;
    private OID authProtocol = AuthMD5.ID;
    private OID privProtocol = PrivDES.ID;
    private OctetString securityName = new OctetString("MD5DES");
    private OctetString privPassphrase = new OctetString(
            "MD5DESUserPrivPassword");
    private OctetString authPassphrase = new OctetString(
            "MD5DESUserAuthPassword");

    public MultiThreadedTrapReceiver() {
        try {
            listen();
        } catch (IOException ex) {
            System.out.println(ex);

        }
    }

    public synchronized void listen() throws IOException {
        AbstractTransportMapping transport;
        if (address instanceof TcpAddress) {
            transport = new DefaultTcpTransportMapping((TcpAddress) address);
        } else {
            transport = new DefaultUdpTransportMapping((UdpAddress) address);
        }
        ThreadPool threadPool = ThreadPool.create("DispatcherPool",
                numDispatcherThreads);
        MessageDispatcher mtDispatcher = new MultiThreadedMessageDispatcher(
                threadPool, new MessageDispatcherImpl());

        // add message processing models
        mtDispatcher.addMessageProcessingModel(new MPv1());
        mtDispatcher.addMessageProcessingModel(new MPv2c());
        mtDispatcher.addMessageProcessingModel(new MPv3(new OctetString(MPv3
                .createLocalEngineID()).getValue()));

        // add all security protocols
        SecurityProtocols.getInstance().addDefaultProtocols();
        SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());

        Snmp snmp = new Snmp(mtDispatcher, transport);
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
                MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);
        // Add the configured user to the USM
        addUsmUser(snmp);

        snmp.addCommandResponder(this);

        transport.listen();

        try {
            this.wait();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }

    private void addUsmUser(Snmp snmp) {
        snmp.getUSM().addUser(
                securityName,
                new UsmUser(securityName, authProtocol, authPassphrase,
                        privProtocol, privPassphrase));
    }

    @Override
    public void processPdu(CommandResponderEvent respEvnt) {
        System.out.println(respEvnt.getPDU());
        InetAddress pduAgentAddress = null;
        // System.out.println(respEvnt.getPDU() + " recieved;");
        // this.setPdu(respEvnt.getPDU());
        OctetString community = new OctetString(respEvnt.getSecurityName());
        System.out.println("community: " + community.toString());

        // handle the SNMP v1
        if (respEvnt.getPDU().getType() == PDU.V1TRAP) {
            Address address = respEvnt.getPeerAddress();
            String hostName = address.toString().split("/")[0];
            int nPort = Integer.parseInt(address.toString().split("/")[1]);
            try {
                pduAgentAddress = InetAddress.getByName(hostName);
            } catch (UnknownHostException ex) {

            }
            System.out.println("hostname: " + pduAgentAddress.getHostAddress()
                    + "; port: " + nPort);
        } else {
            Address address = respEvnt.getPeerAddress();
            String hostName = address.toString().split("/")[0];
            int nPort = Integer.parseInt(address.toString().split("/")[1]);
            try {
                pduAgentAddress = InetAddress.getByName(hostName);
            } catch (UnknownHostException ex) {

            }
            System.out.println("hostname: " + pduAgentAddress.getHostAddress()
                    + "; port: " + nPort);
        }
    }

    public static void main(String[] args) {
        MultiThreadedTrapReceiver trap = new MultiThreadedTrapReceiver();
    }
}

1 个答案:

答案 0 :(得分:0)

我已经改变了 SnmpUtilSendTrapV3 类,

  1. 。使用TcpAddress targetAddress代替Address targetAddress

  2. 使用targetAddress = new TcpAddress(Inet4Address.getLocalHost(), 162);代替targetAddress = GenericAddress.parse("127.0.0.1/164");

  3. TransportMapping transport = new DefaultTcpTransportMapping(); 而不是TransportMapping transport = new DefaultUdpTransportMapping();
  4. 在解决了这个实现错误之后,每次使用snmp.send(pdu,target)发送pdu后,每次ResponseEvent都为null值。

    任何人都有这个问题的解决方案,请帮帮我