From 4138de28c911ce608b482a84ca3ae65954668e45 Mon Sep 17 00:00:00 2001 From: Thomas Casteleyn Date: Tue, 15 Oct 2024 18:55:40 +0200 Subject: [PATCH] feat(inputs.snmp): Convert uneven bytes to int --- internal/snmp/field.go | 45 ++++++++++++++++++++----------------- internal/snmp/field_test.go | 9 ++++++++ 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/internal/snmp/field.go b/internal/snmp/field.go index 936cc3dda4987..e41c3c143ef4e 100644 --- a/internal/snmp/field.go +++ b/internal/snmp/field.go @@ -253,33 +253,38 @@ func (f *Field) Convert(ent gosnmp.SnmpPDU) (interface{}, error) { return v, nil } + var b []byte + switch bit { + case "uint64": + b = make([]byte, 8) + case "uint32": + b = make([]byte, 4) + case "uint16": + b = make([]byte, 2) + default: + return nil, fmt.Errorf("invalid bit value (%s) for hex to int conversion", bit) + } + copy(b, bv) + + var byteOrder binary.ByteOrder switch endian { case "LittleEndian": - switch bit { - case "uint64": - v = binary.LittleEndian.Uint64(bv) - case "uint32": - v = binary.LittleEndian.Uint32(bv) - case "uint16": - v = binary.LittleEndian.Uint16(bv) - default: - return nil, fmt.Errorf("invalid bit value (%s) for hex to int conversion", bit) - } + byteOrder = binary.LittleEndian case "BigEndian": - switch bit { - case "uint64": - v = binary.BigEndian.Uint64(bv) - case "uint32": - v = binary.BigEndian.Uint32(bv) - case "uint16": - v = binary.BigEndian.Uint16(bv) - default: - return nil, fmt.Errorf("invalid bit value (%s) for hex to int conversion", bit) - } + byteOrder = binary.BigEndian default: return nil, fmt.Errorf("invalid Endian value (%s) for hex to int conversion", endian) } + switch bit { + case "uint64": + v = byteOrder.Uint64(b) + case "uint32": + v = byteOrder.Uint32(b) + case "uint16": + v = byteOrder.Uint16(b) + } + return v, nil } diff --git a/internal/snmp/field_test.go b/internal/snmp/field_test.go index c9cdf020974ec..d149731e4dd48 100644 --- a/internal/snmp/field_test.go +++ b/internal/snmp/field_test.go @@ -211,6 +211,15 @@ func TestConvertHextoint(t *testing.T) { }, expected: uint16(0xc884), }, + { + name: "little endian single byte", + conversion: "hextoint:LittleEndian:uint16", + ent: gosnmp.SnmpPDU{ + Type: gosnmp.OctetString, + Value: []byte{0x84}, + }, + expected: uint16(0x84), + }, { name: "little endian invalid", conversion: "hextoint:LittleEndian:invalid",