Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(inputs.snmp): Convert uneven bytes to int #16027

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 25 additions & 20 deletions internal/snmp/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
9 changes: 9 additions & 0 deletions internal/snmp/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading