- 爱易网页
-
Windows教程
- SNMP编程有关问题,无法获取返回的消息
日期:2014-05-16 浏览次数:21041 次
SNMP编程问题,无法获取返回的消息
也就是:stat = SnmpRecvMsg(hSession,&scrEntity,&dstEntity,&recvContext,&recvPdu);总是说消息队列为空,代码如下:
void CTestSnmpView::getUserNumber(HWND h){
SNMPAPI_STATUS stat ;
smiUINT32 majorVersion = 0;
smiUINT32 minorVersion = 0;
smiUINT32 level = 0;
smiUINT32 translateMode = 0;
smiUINT32 retransmitMode = 0;
SNMPAPI_STATUS startResult = SnmpStartup(&majorVersion,&minorVersion,&level,&translateMode,&retransmitMode);
if(SNMPAPI_SUCCESS != startResult){return ;}
//2.建立会话
session = SnmpCreateSession(NULL,NULL,CTestSnmpView::snmp_callback,this);
if(SNMPAPI_FAILURE == session){return ;}
//3.设置传输模式
SnmpSetTranslateMode(SNMPAPI_UNTRANSLATED_V1);
//4.创建实体,一个是本机的ip地址,另一个是接收方的ip地址
HSNMP_ENTITY customEntity = SnmpStrToEntity(session,"127.0.0.1");
HSNMP_ENTITY revEntity = SnmpStrToEntity(session,"192.168.1.1");
if(SNMPAPI_FAILURE == customEntity || SNMPAPI_FAILURE == revEntity){return ;}
//5.设置重传模式,设置为启动重传模式
SnmpSetRetransmitMode(SNMPAPI_ON);
//6.设置超时时间
SnmpSetTimeout(customEntity,1000);
//7.设置重传次数
SnmpSetRetry(customEntity,5);
//8.创建上下文句柄
smiOCTETS community;
community.ptr = (unsigned char *)"public";
community.len = 6;
HSNMP_CONTEXT context = SnmpStrToContext(session,&community);
if(context == SNMPAPI_FAILURE){return ;}
//9.创建变量绑定列表
smiOID sOid;
SnmpStrToOid("1.3.6.1.2.1.1.1.0",&sOid);
HSNMP_VBL vb = SnmpCreateVbl(session,&sOid,NULL);
//11.创建PDU
HSNMP_PDU pdu = SnmpCreatePdu(session,SNMP_PDU_GET,2,NULL,NULL,vb);
//12.发送PDU
stat = SnmpSendMsg(session,customEntity,revEntity,context,pdu);
if(stat == SNMPAPI_FAILURE){return ;}
//
SnmpFreeDescriptor(SNMP_SYNTAX_OID,(smiLPOPAQUE)&sOid);
SnmpFreeEntity(customEntity);
SnmpFreeEntity(revEntity);
SnmpFreeContext(context);
SnmpFreeVbl(vb);
SnmpFreePdu(pdu);
}
回调函数、
SNMPAPI_STATUS CALLBACK CTestSnmpView::snmp_callback(HSNMP_SESSION hSession,HWND hWnd,UINT wMsg,WPARAM wParam,LPARAM lParam,LPVOID lpClientData){
/**接收消息,并且处理1.*/
HSNMP_ENTITY scrEntity;
HSNMP_ENTITY dstEntity;
HSNMP_CONTEXT recvContext;
HSNMP_PDU recvPdu;SNMPAPI_STATUS stat ;
stat = SnmpRecvMsg(hSession,&scrEntity,&dstEntity,&recvContext,&recvPdu);
if (stat != SNMPAPI_SUCCESS){return NULL; }
//2.提取数据报
smiINT pdu_type = 0;
smiINT32 request_id = 0;
smiINT error_status = 0;
smiINT error_index = 0;
HSNMP_VBL vblist = NULL;
stat = SnmpGetPduData(recvPdu,&pdu_type,&request_id,&error_status,&error_index,&vblist);
//3.计算返回列表数目
int count = SnmpCountVbl(vblist);
//4.取回返回结果
smiLPOID name = NULL;
smiLPVALUE value = NULL;
for(int i=0;i<count;i++){
SnmpGetVb(vblist,i,name,value);
}
//5.释放句柄,回收内存
SnmpClose(hSession);
SnmpCleanup();
return NULL;
}
初学,望大神指点啊