异步采数据 asynchapp程序

1、snmp_session结构

struct snmp_session {

   long            version; /** snmpversion */

   int             retries; /**Number of retries before timeout. */

   long            timeout;    /** Number of uS until first timeout, thenexponential backoff */

   u_long          flags;

   struct snmp_session *subsession;

   struct snmp_session *next;

   char           *peername;

   u_short         remote_port;

   char           *localname;    /** My Domain name or dotted IP address, 0for default */

   u_short         local_port;

   u_char         *(*authenticator)(u_char *, size_t *, u_char *, size_t);

 /**     * Authentication function or NULL if nullauthentication is used   */

   netsnmp_callback callback; /** Function to interpret incoming data */

 

   void           *callback_magic;/*Pointer to data that the callback function may consider important*/

   int             s_errno; /** copyof system errno */

    int             s_snmp_errno;   /** copy of library errno */

   long            sessid; /** Session id - AgentXonly */

 

   /*     * SNMPv1 & SNMPv2cfields     */

   u_char         *community; /**community for outgoing requests. */

   size_t          community_len; /**Length of community name. */

   size_t          rcvMsgMaxSize;/**  Largest message to try toreceive.  */

   size_t          sndMsgMaxSize;/**  Largest message to try to send.  */

 

   /*     * SNMPv3 fields     */

   u_char          isAuthoritative;/** are we the authoritative engine? */

   u_char         *contextEngineID;/** authoritative snmpEngineID */

   size_t         contextEngineIDLen; /** Length of contextEngineID */

   u_int           engineBoots; /**initial engineBoots for remote engine */

   u_int           engineTime; /**initial engineTime for remote engine */

   char           *contextName;  /** authoritative contextName */

   size_t          contextNameLen;/** Length of contextName */

   u_char         *securityEngineID;   /** authoritative snmpEngineID */

   size_t         securityEngineIDLen; /** Length of contextEngineID */

   char           *securityName; /**on behalf of this principal */

   size_t          securityNameLen;/** Length of securityName. */

    oid            *securityAuthProto; /** authprotocol oid */

    size_t          securityAuthProtoLen; /** Length ofauth protocol oid */

   u_char         securityAuthKey[USM_AUTH_KU_LEN]; /** Ku for auth protocol XXX */

   size_t          securityAuthKeyLen; /** Length of Kufor auth protocol */

   u_char         *securityAuthLocalKey; /** Kul for auth protocol */

   size_t         securityAuthLocalKeyLen; /** Length of Kul for auth protocol XXX */

   oid            *securityPrivProto;  /** priv protocol oid */

   size_t         securityPrivProtoLen; /** Length of priv protocol oid */

   u_char         securityPrivKey[USM_PRIV_KU_LEN]; /** Ku for privacy protocol XXX */

   size_t          securityPrivKeyLen;/** Length of Ku for priv protocol */

   u_char         *securityPrivLocalKey; /** Kul for priv protocol */

   size_t         securityPrivLocalKeyLen; /** Length of Kul for priv protocol XXX */

   int             securityModel; /**snmp security model, v1, v2c, usm */

   int             securityLevel; /**noAuthNoPriv, authNoPriv, authPriv */

   char           *paramName; /**target param name */

   void           *securityInfo; /*security module specific     */

   structnetsnmp_container_s *transport_configuration;   /* transport specific configuration */

   void           *myvoid;    /*use as you want data*/

};

 

2、netsnmp_pdu结构

typedef struct snmp_pdu {

#define non_repeaters   errstat

#define max_repetitions errindex

   /** Protocol-version independent fields*/

   long            version; /** snmpversion */

   int             command; /** Typeof this PDU */

   long            reqid;    /** Request id - note: not incremented onretries */

   long            msgid; /** Messageid for V3 messages note: incremented for each retry */

   long            transid; /**Unique ID for incoming transactions */

   long            sessid; /**Session id for AgentX messages */

   long            errstat;    /** Error status (non_repeaters in GetBulk)*/

   long            errindex; /**Error index (max_repetitions in GetBulk) */

   u_long          time; /** Uptime*/

   u_long          flags;

   int             securityModel;

   int             securityLevel; /**noAuthNoPriv, authNoPriv, authPriv */

int             msgParseModel;

 

    /*Transport-specific opaque data.  Thisreplaces the IP-centric address * field. */

   void           *transport_data;

int             transport_data_length;

 

    /* The actualtransport domain.  This SHOULD NOT BEFREE()D. */

   const oid      *tDomain;

   size_t          tDomainLen;

netsnmp_variable_list*variables;

 

        /* * SNMPv1 & SNMPv2c fields */

   u_char         *community; /**community for outgoing requests. */

size_t          community_len;  /** length of community name. */

 

       /* Trap information*/

   oid            *enterprise; /**System OID */

   size_t          enterprise_length;

   long            trap_type; /**trap type */

   long           specific_type;  /** specific type*/

unsigned char   agent_addr[4]; /** This is ONLY used for v1TRAPs  */

 

            /* SNMPv3 fields */

   u_char         *contextEngineID;/** context snmpEngineID */

   size_t         contextEngineIDLen;  /** Length ofcontextEngineID */

   char           *contextName; /**authoritative contextName */

   size_t          contextNameLen;/** Length of contextName */

   u_char         *securityEngineID;/** authoritative snmpEngineID for security */

   size_t         securityEngineIDLen; /** Length of securityEngineID */

   char           *securityName; /**on behalf of this principal */

   size_t          securityNameLen;/** Length of securityName. */

} netsnmp_pdu;

 

3.netsnmp_variable_list结构

typedef struct variable_list {

     struct variable_list *next_variable; /** NULL for last variable */

     oid            *name; /** Objectidentifier of variable */

     size_t          name_length; /**number of subid's in name */

     u_char          type; /** ASN typeof variable */

     netsnmp_vardata val; /** value of variable */

     size_t          val_len; /** thelength of the value to be copied into buf */

     oid            name_loc[MAX_OID_LEN]; /** buffer to hold the OID */

     u_char          buf[40]; /** 90percentile < 40. */

     void           *data; /** (Opaque)hook for additional data */

     void           (*dataFreeHook)(void *);/** callback to free above */

 int            index;

} netsnmp_variable_list;

 

4. Netsnmp_vardata结构

typedefunion {

   long           *integer;

   u_char         *string;

   oid            *objid;

   u_char         *bitstring;

   struct counter64 *counter64;

      #ifdef NETSNMP_WITH_OPAQUE_SPECIAL_TYPES

        float          *floatVal;

        double         *doubleVal;

           /** t_union *unionVal;     */

      #endif                          /*NETSNMP_WITH_OPAQUE_SPECIAL_TYPES */

}netsnmp_vardata;

 

5.asynchapp.c

#include <net-snmp/net-snmp-config.h>

#include<net-snmp/net-snmp-includes.h>

 

/** a list of hosts to query */

struct host {

  constchar *name;

 const char *community;

} hosts[] = {

  {"test1",                     "public"},

  {"test2",                     "public"},

  {"test3",                     "public"},

  {"test4",                     "public"},

  {NULL }

};

 

/* * a list of variables to query for */

struct oid {

 const char *Name;

  oid Oid[MAX_OID_LEN];

  intOidLen;

} oids[] = {

  {"system.sysDescr.0" },

  {"interfaces.ifNumber.1" },

  {"interfaces.ifNumber.0" },

  {NULL }

};

/* * initialize */

void initialize (void)

{

 struct oid *op = oids;

 

  /*Win32: init winsock */

 SOCK_STARTUP;

 

  /*initialize library */

 init_snmp("asynchapp");

 

  /*parse the oids */

 while (op->Name) {

   op->OidLen = sizeof(op->Oid)/sizeof(op->Oid[0]);

    if(!read_objid(op->Name, op->Oid, &op->OidLen)) {

     snmp_perror("read_objid");

      exit(1);

    }

   op++;

  }

}

 

/* * simple printing of returned data */

int print_result (int status, structsnmp_session *sp, struct snmp_pdu *pdu)

{

  charbuf[1024];

 struct variable_list *vp;

  intix;

 struct timeval now;

 struct timezone tz;

  structtm *tm;

 

 gettimeofday(&now, &tz);

  tm =localtime(&now.tv_sec);

 fprintf(stdout, "%.2d:%.2d:%.2d.%.6d ", tm->tm_hour,tm->tm_min, tm->tm_sec,

         now.tv_usec);

 switch (status) {

  caseSTAT_SUCCESS:

    vp= pdu->variables;

     while (vp) {    if (pdu->errstat == SNMP_ERR_NOERROR) {

       snprint_variable(buf, sizeof(buf), vp->name, vp->name_length, vp);

       fprintf(stdout, "%s: %s\n", sp->peername, buf);

           vp= vp->next_variable;

     }

    }

   else {

     for (ix = 1; vp && ix != pdu->errindex; vp =vp->next_variable, ix++)

       ;

     if (vp) snprint_objid(buf, sizeof(buf), vp->name,vp->name_length);

     else strcpy(buf, "(none)");

     fprintf(stdout, "%s: %s: %s\n",

              sp->peername, buf,snmp_errstring(pdu->errstat));

    }

   return 1;

  caseSTAT_TIMEOUT:

   fprintf(stdout, "%s: Timeout\n", sp->peername);

   return 0;

  caseSTAT_ERROR:

   snmp_perror(sp->peername);

   return 0;

  }

 return 0;

}

 

/************************************** pollall hosts in parallel */

struct session {

 struct snmp_session *sess;                    /*SNMP session data */

 struct oid *current_oid;                /*How far in our poll are we */

} sessions[sizeof(hosts)/sizeof(hosts[0])];

 

int active_hosts;                       /* hosts that we have not completed */

 

/* response handler */

int asynch_response(int operation, structsnmp_session *sp, int reqid,

                         struct snmp_pdu *pdu, void *magic)

{

 struct session *host = (struct session *)magic;

 struct snmp_pdu *req;

 

  if(operation == NETSNMP_CALLBACK_OP_RECEIVED_MESSAGE) {

    if(print_result(STAT_SUCCESS, host->sess, pdu)) {

     host->current_oid++;                                /*send next GET (if any) */

     if (host->current_oid->Name) {

           req= snmp_pdu_create(SNMP_MSG_GET);

           snmp_add_null_var(req,host->current_oid->Oid, host->current_oid->OidLen);

           if(snmp_send(host->sess, req))

             return 1;

           else{

             snmp_perror("snmp_send");

             snmp_free_pdu(req);

           }

     }

    }

  }

  else

   print_result(STAT_TIMEOUT, host->sess, pdu);

 

  /*something went wrong (or end of variables)

   *this host not active any more

   */

 active_hosts--;

 return 1;

}

 

void asynchronous(void)

{

 struct session *hs;

 struct host *hp;

 

  /*startup all hosts */

 

  for(hs = sessions, hp = hosts; hp->name; hs++, hp++) {

   struct snmp_pdu *req;

   struct snmp_session sess;

   snmp_sess_init(&sess);                       /*initialize session */

   sess.version = SNMP_VERSION_2c;

   sess.peername = strdup(hp->name);

   sess.community = strdup(hp->community);

   sess.community_len = strlen(sess.community);

   sess.callback = asynch_response;               /*default callback */

   sess.callback_magic = hs;

    if(!(hs->sess = snmp_open(&sess))) {

     snmp_perror("snmp_open");

     continue;

    }

   hs->current_oid = oids;

   req = snmp_pdu_create(SNMP_MSG_GET);        /*send the first GET */

   snmp_add_null_var(req, hs->current_oid->Oid,hs->current_oid->OidLen);

    if(snmp_send(hs->sess, req))

     active_hosts++;

   else {

     snmp_perror("snmp_send");

     snmp_free_pdu(req);

    }

  }

 

  /*loop while any active hosts */

 

 while (active_hosts) {

   int fds = 0, block = 1;

   fd_set fdset;

   struct timeval timeout;

 

   FD_ZERO(&fdset);

   snmp_select_info(&fds, &fdset, &timeout, &block);

   fds = select(fds, &fdset, NULL, NULL, block ? NULL : &timeout);

    if(fds < 0) {

       perror("select failed");

       exit(1);

    }

    if(fds)

       snmp_read(&fdset);

    else

       snmp_timeout();

  }

 

  /*cleanup */

 

  for(hp = hosts, hs = sessions; hp->name; hs++, hp++) {

    if(hs->sess) snmp_close(hs->sess);

  }

}

 

/*****************************************************************************/

int main (int argc,char **argv)

{

 initialize();

 

 printf("---------- asynchronous -----------\n");

 asynchronous();

 

 return 0;

}

 

6、Makefile文件

CC=gcc

OBJS3=asyncapp.o

TARGETS= asyncapp

CFLAGS=-I. `net-snmp-config --cflags`

BUILDLIBS=`net-snmp-config --libs`

# shared library flags (assumes gcc)

DLFLAGS=-fPIC -shared

all: $(TARGETS)

 

 

asyncapp: $(OBJS3)

           $(CC) -o asyncapp $(OBJS3) $(BUILDLIBS)

 

clean:

           rm  $(TARGETS)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值