SNMP常用数据操作

时间:2023-03-10 07:02:24
SNMP常用数据操作

SNMP常用数据操作

snmp编程中常见的数据类型基本上就是integer32/oct_str(字节数组)/counter64/timeticks/dateAndTime这些。很多其它的比如TruthValue这样的数据在编程的时候一般都比较少用,而且一般都有对应的替代。

Counter32类型

Counter32其实对应C语言中的32位无符号整型(0~2^32-1)。在snmpv1中它的解释是:“计数器是一个非负的整数,它递增至最大值,而后归零”。

对counter32的操作,在32位机器上,其一般使用unsigned int来表示。是比较简单的数据类型,所以无需使用特别的操作。

Counter64类型

Counter64对应64位的计数器,它表示的范围(0~2^64-1)就比counter32大多了,在net-snmp中提供了对它操作的相关函数。

Net-snmp中并没有直接使用C语言中的64位无符号整型,而是使用了一个结构体来表示

    struct counter64 {
u_long high;
u_long low;
};

为什么这么做呢?这个不好说,可能是为了操作方便吧。在snmp++中定义了一个类Counter64来提供对这个数据类型的操作,它也是如同此处将其分为高位部分(hipart)和低位(lopart)部分。

同时还定义了一些用于操作counter64数据类型的函数。

 typedef struct counter64 U64;

#define I64CHARSZ 21

    void            divBy10(U64, U64 *, unsigned int *);
void multBy10(U64, U64 *);
void incrByU16(U64 *, unsigned int);
void incrByU32(U64 *, unsigned int);
NETSNMP_IMPORT
void zeroU64(U64 *);
int isZeroU64(const U64 *);
NETSNMP_IMPORT
void printU64(char *, const U64 *);
NETSNMP_IMPORT
void printI64(char *, const U64 *);
int read64(U64 *, const char *);
NETSNMP_IMPORT
void u64Subtract(const U64 * pu64one, const U64 * pu64two,
U64 * pu64out);
void u64Incr(U64 * pu64out, const U64 * pu64one);
void u64UpdateCounter(U64 * pu64out, const U64 * pu64one,
const U64 * pu64two);
void u64Copy(U64 * pu64one, const U64 * pu64two); int netsnmp_c64_check_for_32bit_wrap(U64 *old_val, U64 *new_val,
int adjust);
NETSNMP_IMPORT
int netsnmp_c64_check32_and_update(struct counter64 *prev_val,
struct counter64 *new_val,
struct counter64 *old_prev_val,
int *need_wrap_check);

在net-snmp中对Counter64数据的操作应该使用下面的函数来进行,而不用直接使用unsigned long long等原生的数据类型。为什么要这么做呢?因为这涉及到将counter64数据的解析转换等操作。

具体可见asn_build_unsigned_int64函数,它在net-snmp-5.7.3\snmplib\asn1.c文件中。

u_char         *
asn_build_unsigned_int64(u_char * data,
size_t * datalength,
u_char type,
const struct counter64 * cp, size_t countersize)

time ticks类型

time ticks:是一个时间单位,表示以0.01秒为单位计算的时间;

这其实就是一个32位无符号整型。这里要注意一下的是它的单位,在使用的时候应该进行单位换算。

DateAndTime类型

这是一个用来表示时间的数据类型,长度为11个字节。

在snmp中有具体的规定,每一个字节表示什么。

以前解释过它,这里就不详述的了。可用看这里http://www.cnblogs.com/oloroso/p/4595127.html