⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snmpv1communicationinterface.java

📁 基于snmp/mib的网络数据获取系统设计与实现
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/*
 * SNMP Package
 *
 * Copyright (C) 2004, Jonathan Sevy <jsevy@mcs.drexel.edu>
 *
 * This is free software. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that the following conditions
 * are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice, this
 *     list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation 
 *     and/or other materials provided with the distribution.
 *  3. The name of the author may not be used to endorse or promote products 
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */


package snmp;

import java.io.*;
import java.net.*;


/**
*    The class SNMPv1CommunicationInterface defines methods for communicating with SNMP entities.
*    The approach is that from version 1 of SNMP, using no encryption of data. Communication occurs
*    via UDP, using port 161, the standard SNMP port.
*/

public class SNMPv1CommunicationInterface
{
    public static final int SNMPPORT = 161;
    
    // largest size for datagram packet payload; based on
    // RFC 1157, need to handle messages of at least 484 bytes
    private int receiveBufferSize = 512;
    
    private int version;
    private InetAddress hostAddress;
    private String community;
    DatagramSocket dSocket;
    
    public int requestID = 1;
            
    
    
    
    /**
    *    Construct a new communication object to communicate with the specified host using the
    *    given community name. The version setting should be either 0 (version 1) or 1 (version 2,
    *    a la RFC 1157).
    */
    
    public SNMPv1CommunicationInterface(int version, InetAddress hostAddress, String community)
        throws SocketException
    {
        this.version = version;
        this.hostAddress = hostAddress;
        this.community = community;
        
        dSocket = new DatagramSocket();
        dSocket.setSoTimeout(15000);    //15 seconds
    }
    
    
    
    
    /**
    *    Permits setting timeout value for underlying datagram socket (in milliseconds).
    */
    
    public void setSocketTimeout(int socketTimeout)
        throws SocketException
    {
        dSocket.setSoTimeout(socketTimeout);
    }
    
    
    
    /**
    *    Close the "connection" with the device.
    */
    
    public void closeConnection()
        throws SocketException
    {
        dSocket.close();
    }

    
    
    
    
    
    /**
    *    Retrieve all MIB variable values subsequent to the starting object identifier
    *    given in startID (in dotted-integer notation). Return as SNMPVarBindList object.
    *    Uses SNMPGetNextRequests to retrieve variable values in sequence.
    *    @throws IOException Thrown when timeout experienced while waiting for response to request.
    *    @throws SNMPBadValueException 
    */
    
    public SNMPVarBindList retrieveAllMIBInfo(String startID)
        throws IOException, SNMPBadValueException
    {
        // send GetNextRequests until receive
        // an error message or a repeat of the object identifier we sent out
        SNMPVarBindList retrievedVars = new SNMPVarBindList();
        
        
        int errorStatus = 0;
        int errorIndex = 0;
        
        SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(startID);
        SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPNull());
        SNMPSequence varList = new SNMPSequence();
        varList.addSNMPObject(nextPair);
        SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETNEXTREQUEST, requestID, errorStatus, errorIndex, varList);
        SNMPMessage message = new SNMPMessage(version, community, pdu);
        byte[] messageEncoding = message.getBEREncoding();
        DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT);
        
        
        dSocket.send(outPacket);
        
        
        
        while (errorStatus == 0)
        {
            
            DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);
        
            dSocket.receive(inPacket);
            
            byte[] encodedMessage = inPacket.getData();
            
            
            SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value);
            //errorStatus = ((BigInteger)((SNMPInteger)((receivedMessage.getPDU()).getSNMPObjectAt(1))).getValue()).intValue();
            
            
            varList = (receivedMessage.getPDU()).getVarBindList();
            SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0));
            
            SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0));
            SNMPObject newValue = newPair.getSNMPObjectAt(1);
            
            retrievedVars.addSNMPObject(newPair);
            
            
            if (requestedObjectIdentifier.equals(newObjectIdentifier))
                break;
                
            requestedObjectIdentifier = newObjectIdentifier;
        
            requestID++;
            nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPNull());
            varList = new SNMPSequence();
            varList.addSNMPObject(nextPair);
            pdu = new SNMPPDU(SNMPBERCodec.SNMPGETNEXTREQUEST, requestID, errorStatus, errorIndex, varList);
            message = new SNMPMessage(version, community, pdu);
            messageEncoding = message.getBEREncoding();
            outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT);
            
            dSocket.send(outPacket);
            
        }
            
        
        return retrievedVars;
        
    }
    
    
    
    private String hexByte(byte b)
    {
        int pos = b;
        if (pos < 0)
            pos += 256;
        String returnString = new String();
        returnString += Integer.toHexString(pos/16);
        returnString += Integer.toHexString(pos%16);
        return returnString;
    }
    
    
    
    
    
    /**
    *    Retrieve the MIB variable value corresponding to the object identifier
    *    given in itemID (in dotted-integer notation). Return as SNMPVarBindList object; if no
    *    such variable (either due to device not supporting it, or community name having incorrect
    *    access privilege), SNMPGetException thrown
    *    @throws IOException Thrown when timeout experienced while waiting for response to request.
    *    @throws SNMPBadValueException 
    *   @throws SNMPGetException Thrown if supplied OID has value that can't be retrieved
    */
    
    public SNMPVarBindList getMIBEntry(String itemID)
        throws IOException, SNMPBadValueException, SNMPGetException
    {
        // send GetRequest to specified host to retrieve specified object identifier
        
        SNMPVarBindList retrievedVars = new SNMPVarBindList();
        
        
        int errorStatus = 0;
        int errorIndex = 0;
        
        
        SNMPObjectIdentifier requestedObjectIdentifier = new SNMPObjectIdentifier(itemID);
        SNMPVariablePair nextPair = new SNMPVariablePair(requestedObjectIdentifier, new SNMPNull());
        SNMPSequence varList = new SNMPSequence();
        varList.addSNMPObject(nextPair);
        SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETREQUEST, requestID, errorStatus, errorIndex, varList);
        
        SNMPMessage message = new SNMPMessage(version, community, pdu);
        
        byte[] messageEncoding = message.getBEREncoding();
        
        
        /*
        System.out.println("Request Message bytes:");
        
        for (int i = 0; i < messageEncoding.length; ++i)
            System.out.print(hexByte(messageEncoding[i]) + " ");
        */
        
        DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, hostAddress, SNMPPORT);
        
        dSocket.send(outPacket);
        
        
        while (true)    // wait until receive reply for requestID & OID (or error)
        {
            
            DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);
            
            dSocket.receive(inPacket);
            
            byte[] encodedMessage = inPacket.getData();
            
            /*
            System.out.println("Message bytes:");
            
            for (int i = 0; i < encodedMessage.length; ++i)
            {
                System.out.print(hexByte(encodedMessage[i]) + " ");
            }
            */
            
            
            SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value);
            SNMPPDU receivedPDU = receivedMessage.getPDU();
            
            // check request identifier; if incorrect, just ignore packet and continue waiting
            if (receivedPDU.getRequestID() == requestID)
            {
                
                // check error status; if retrieval problem, throw SNMPGetException
                if (receivedPDU.getErrorStatus() != 0)
                    throw new SNMPGetException("OID " + itemID + " not available for retrieval", receivedPDU.getErrorIndex(), receivedPDU.getErrorStatus());        
                
                
                varList = receivedPDU.getVarBindList();
                SNMPSequence newPair = (SNMPSequence)(varList.getSNMPObjectAt(0));
                
                SNMPObjectIdentifier newObjectIdentifier = (SNMPObjectIdentifier)(newPair.getSNMPObjectAt(0));
                SNMPObject newValue = newPair.getSNMPObjectAt(1);
                
                // check the object identifier to make sure the correct variable has been received;
                // if not, just continue waiting for receive
                if (newObjectIdentifier.toString().equals(itemID))
                {
                    // got the right one; add it to retrieved var list and break!
                    retrievedVars.addSNMPObject(newPair);
                    break;
                }
            
            }
            
        }
        
        
        requestID++;
        
        
        return retrievedVars;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -