gpt4 book ai didi

c++ - 如何在 net-snmp 中打印整数和 Counter32 值

转载 作者:太空狗 更新时间:2023-10-29 23:08:41 27 4
gpt4 key购买 nike

我创建了这段打印字符串值的代码,它运行良好:

 add_mibdir("."); 
pdu = snmp_pdu_create(SNMP_MSG_GET);

read_objid(if_index, id_oid, &id_len);
snmp_add_null_var(pdu, id_oid, id_len);
status = snmp_synch_response(sess_handle,pdu,&response);

int count=1;
for(vars = response->variables; vars; vars = vars->next_variable)
{
if (vars->type == ASN_OCTET_STR)
{
char *sp = (char *)malloc(1 + vars->val_len);
memcpy(sp, vars->val.string, vars->val_len);
sp[vars->val_len] = '\0';
printf("value #%d is a string: %s\n", count++, sp);
printf("%s\n",vars->val.string);
free(sp);
}

}

示例:对于 SNMPv2-SMI::mib-2.47.1.1.1.1.2.1012 = STRING: "GigabitEthernet Container",它返回 "GigabitEthernet Container";

但我尝试了一个整数值,但没有成功:

for(vars = response->variables; vars; vars = vars->next_variable)
printf("%ld",(long int)vars->val.integer);//it returns large numbers;

示例:对于 SNMPv2-SMI::mib-2.17.2.11.0 = INTEGER: 1500,我想返回 1500,对于 IF-MIB::ifOutBroadcastPkts.10103 = Counter32: 14011112 我想返回 14011112

如果我使用:

for(vars = response->variables; vars; vars = vars->next_variable)
print_variable(vars->name, vars->name_length, vars);

它返回Counter32:12132,或INTEGER:12324,或STRING:Gi0/1(但我想解析这个结果并将它用到一些没有数据类型的变量中,例如:在 var a 中存储 12132)。

谢谢!

最佳答案

如果有人仍然对此有疑问,我想出了一个不需要使用 net-snmp 5.7.3 进行解析的替代机制:

template<typename T>
static boost::shared_ptr< std::vector<T> > GetVector(std::string user_oid, struct snmp_session * snmp_session) {

// Other Initialization ....

char temp_buf[BUFSIZ];
size_t temp_buf_len = BUFSIZ;
bool orig_config_val_qp = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT);
bool orig_config_val_bv = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE);

// Enforce this for correct output in snprint_variable functions
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, 1);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE, 1);

// oid conversion routines ...

// Processing loop for response vars (similar to netsnmp/app/snmpbulkwalk.c) ...
if (vars->type == ASN_OCTET_STR)
{
temp_buf_len = BUFSIZ;
snprint_variable(temp_buf, temp_buf_len, vars->name, vars->name_length, vars);
result->push_back(boost::lexical_cast<T>(temp_buf));
}
// End Processing loop...

// Restore configuration
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, orig_config_val_qp);
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_BARE_VALUE, orig_config_val_bv);

return result;
}

这将使您的应用程序配置的其余部分保持原样,并且只吐出值,因此您不需要标记化。我缩短了循环,以便它专注于重要方面。

关于c++ - 如何在 net-snmp 中打印整数和 Counter32 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8562801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com