### Quick Start - Running a Basic SNMP Server Source: https://context7.com/slayercat/gosnmpserver/llms.txt This example demonstrates how to set up and run a basic SNMP server with built-in MIBs using GoSNMPServer. ```APIDOC ## Quick Start - Running a Basic SNMP Server Create and run a complete SNMP server with built-in MIBs. ```go package main import ( "github.com/gosnmp/gosnmp" "github.com/slayercat/GoSNMPServer" "github.com/slayercat/GoSNMPServer/mibImps" ) func main() { // Create the master agent with security configuration master := GoSNMPServer.MasterAgent{ Logger: GoSNMPServer.NewDefaultLogger(), SecurityConfig: GoSNMPServer.SecurityConfig{ AuthoritativeEngineBoots: 1, Users: []gosnmp.UsmSecurityParameters{ { UserName: "testuser", AuthenticationProtocol: gosnmp.MD5, PrivacyProtocol: gosnmp.DES, AuthenticationPassphrase: "testauth", PrivacyPassphrase: "testpriv", }, }, }, SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{"public"}, OIDs: mibImps.All(), }, }, } // Create and start the server server := GoSNMPServer.NewSNMPServer(master) err := server.ListenUDP("udp", "127.0.0.1:1161") if err != nil { panic(err) } server.ServeForever() } ``` ``` -------------------------------- ### Install and Run GoSNMPServer Source: https://github.com/slayercat/gosnmpserver/blob/master/README.md Installs the GoSNMPServer command-line tool and demonstrates how to run a basic SNMP server and query it using snmpwalk. ```shell go install github.com/slayercat/GoSNMPServer/cmd/gosnmpserver $(go env GOPATH)/bin/gosnmpserver run-server snmpwalk -v 3 -l authPriv -n public -u testuser -a md5 -A testauth -x des -X testpriv 127.0.0.1:1161 1 ``` -------------------------------- ### Initialize and Run a Basic SNMP Server Source: https://context7.com/slayercat/gosnmpserver/llms.txt Demonstrates setting up a MasterAgent with security configurations and starting the server on a UDP port. ```go package main import ( "github.com/gosnmp/gosnmp" "github.com/slayercat/GoSNMPServer" "github.com/slayercat/GoSNMPServer/mibImps" ) func main() { // Create the master agent with security configuration master := GoSNMPServer.MasterAgent{ Logger: GoSNMPServer.NewDefaultLogger(), SecurityConfig: GoSNMPServer.SecurityConfig{ AuthoritativeEngineBoots: 1, Users: []gosnmp.UsmSecurityParameters{ { UserName: "testuser", AuthenticationProtocol: gosnmp.MD5, PrivacyProtocol: gosnmp.DES, AuthenticationPassphrase: "testauth", PrivacyPassphrase: "testpriv", }, }, }, SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{"public"}, OIDs: mibImps.All(), }, }, } // Create and start the server server := GoSNMPServer.NewSNMPServer(master) err := server.ListenUDP("udp", "127.0.0.1:1161") if err != nil { panic(err) } server.ServeForever() } ``` -------------------------------- ### Configure and Start SNMP Server Source: https://github.com/slayercat/gosnmpserver/blob/master/README.md Sets up a master agent with security configurations for SNMPv3 and defines sub-agents with community IDs and OIDs. It then starts the SNMP server and listens for incoming UDP requests. ```golang master := GoSNMPServer.MasterAgent{ Logger: GoSNMPServer.NewDefaultLogger(), SecurityConfig: GoSNMPServer.SecurityConfig{ AuthoritativeEngineBoots: 1, Users: []gosnmp.UsmSecurityParameters{ { UserName: c.String("v3Username"), AuthenticationProtocol: gosnmp.MD5, PrivacyProtocol: gosnmp.DES, AuthenticationPassphrase: c.String("v3AuthenticationPassphrase"), PrivacyPassphrase: c.String("v3PrivacyPassphrase"), }, }, }, SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{c.String("community")}, OIDs: mibImps.All(), }, }, } server := GoSNMPServer.NewSNMPServer(master) er := server.ListenUDP("udp", "127.0.0.1:1161") if err != nil { logger.Errorf("Error in listen: %+v", err) } server.ServeForever() ``` -------------------------------- ### Test SNMP Server with CLI Tools Source: https://context7.com/slayercat/gosnmpserver/llms.txt Commands for installing the server and performing walk/get/set operations using standard net-snmp utilities. ```bash # Install the server go install github.com/slayercat/GoSNMPServer/cmd/gosnmpserver # Run the example server gosnmpserver run-server --bindTo 127.0.0.1:1161 # SNMPv2c walk with community string snmpwalk -v 2c -c public 127.0.0.1:1161 1 # SNMPv3 walk with authentication and privacy snmpwalk -v 3 -l authPriv -u testuser -a MD5 -A testauth -x DES -X testpriv 127.0.0.1:1161 1 # Get specific OID snmpget -v 2c -c public 127.0.0.1:1161 1.3.6.1.2.1.1.1.0 # Set value (if writable OID is configured) snmpset -v 2c -c public 127.0.0.1:1161 1.3.6.1.4.1.12345.1.1 i 100 ``` -------------------------------- ### Start Server Loop Source: https://context7.com/slayercat/gosnmpserver/llms.txt Initiates the blocking server loop to process incoming SNMP requests. ```go server := GoSNMPServer.NewSNMPServer(master) err := server.ListenUDP("udp", "127.0.0.1:1161") if err != nil { log.Fatalf("Listen error: %v", err) } // Blocking call - handles requests forever err = server.ServeForever() if err != nil { log.Printf("Server stopped: %v", err) } ``` -------------------------------- ### ServeForever Source: https://context7.com/slayercat/gosnmpserver/llms.txt Starts the main server loop to handle incoming SNMP requests indefinitely. This is a blocking call that processes requests until the server is shut down or an error occurs. ```APIDOC ## ServeForever Starts the main server loop to handle incoming SNMP requests indefinitely. This is a blocking call that processes requests until the server is shut down or an error occurs. ```go server := GoSNMPServer.NewSNMPServer(master) er := server.ListenUDP("udp", "127.0.0.1:1161") if err != nil { log.Fatalf("Listen error: %v", err) } // Blocking call - handles requests forever err = server.ServeForever() if err != nil { log.Printf("Server stopped: %v", err) } ``` ``` -------------------------------- ### Define Custom OID with Get Handler Source: https://github.com/slayercat/gosnmpserver/blob/master/README.md Appends a custom OID to a SubAgent, specifying its type, a function to retrieve its value on GET requests, and a documentation string. This example shows how to define an 'ifIndex' OID. ```golang { OID: fmt.Sprintf("1.3.6.1.2.1.2.2.1.1.%d", ifIndex), Type: gosnmp.Integer, OnGet: func() (value interface{}, err error) { return GoSNMPServer.Asn1IntegerWrap(ifIndex), nil }, Document: "ifIndex", } ``` -------------------------------- ### Create a New SNMP Server Instance Source: https://context7.com/slayercat/gosnmpserver/llms.txt Instantiates a new server using a configured MasterAgent. Note that this function will panic if the provided configuration is invalid. ```go import "github.com/slayercat/GoSNMPServer" master := GoSNMPServer.MasterAgent{ Logger: GoSNMPServer.NewDefaultLogger(), SecurityConfig: GoSNMPServer.SecurityConfig{ AuthoritativeEngineBoots: 1, }, SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{"public"}, OIDs: []*GoSNMPServer.PDUValueControlItem{}, }, }, } server := GoSNMPServer.NewSNMPServer(master) ``` -------------------------------- ### Configure Logging Source: https://context7.com/slayercat/gosnmpserver/llms.txt Set up logging using default, discard, or wrapped logrus loggers. The logger can be assigned to a MasterAgent. ```go import ( "github.com/sirupsen/logrus" "github.com/slayercat/GoSNMPServer" ) // Use default logger (outputs to stdout at Trace level) logger := GoSNMPServer.NewDefaultLogger() // Use discard logger (silent - no output) silentLogger := GoSNMPServer.NewDiscardLogger() // Wrap existing logrus logger with custom configuration customLogrus := logrus.New() customLogrus.Level = logrus.InfoLevel customLogrus.SetFormatter(&logrus.JSONFormatter{}) logger = GoSNMPServer.WrapLogrus(customLogrus) // Adjust log level on default logger defaultLogger := GoSNMPServer.NewDefaultLogger() defaultLogger.(*GoSNMPServer.DefaultLogger).Level = logrus.DebugLevel // Use in MasterAgent master := GoSNMPServer.MasterAgent{ Logger: logger, // ... } ``` -------------------------------- ### Implement a Custom Monitoring Server in Go Source: https://context7.com/slayercat/gosnmpserver/llms.txt Defines custom OIDs with callback functions for data retrieval and initializes a MasterAgent with security configurations. Requires the gosnmp and GoSNMPServer packages. ```go package main import ( "log" "os" "os/signal" "runtime" "sync/atomic" "syscall" "time" "github.com/gosnmp/gosnmp" "github.com/slayercat/GoSNMPServer" "github.com/slayercat/GoSNMPServer/mibImps" ) var requestCount uint64 func main() { logger := GoSNMPServer.NewDefaultLogger() // Custom OIDs for application monitoring customOIDs := []*GoSNMPServer.PDUValueControlItem{ { OID: "1.3.6.1.4.1.99999.1.1", Type: gosnmp.OctetString, OnGet: func() (interface{}, error) { return GoSNMPServer.Asn1OctetStringWrap("MyApp v1.0.0"), nil }, Document: "appVersion", }, { OID: "1.3.6.1.4.1.99999.1.2", Type: gosnmp.TimeTicks, OnGet: func() (interface{}, error) { uptime := time.Since(startTime).Seconds() * 100 return GoSNMPServer.Asn1TimeTicksWrap(uint32(uptime)), nil }, Document: "appUptime", }, { OID: "1.3.6.1.4.1.99999.1.3", Type: gosnmp.Counter64, OnGet: func() (interface{}, error) { count := atomic.LoadUint64(&requestCount) return GoSNMPServer.Asn1Counter64Wrap(count), nil }, Document: "requestCount", }, { OID: "1.3.6.1.4.1.99999.1.4", Type: gosnmp.Gauge32, OnGet: func() (interface{}, error) { var m runtime.MemStats runtime.ReadMemStats(&m) return GoSNMPServer.Asn1Gauge32Wrap(uint(m.Alloc / 1024)), nil }, Document: "memoryUsageKB", }, { OID: "1.3.6.1.4.1.99999.1.5", Type: gosnmp.Integer, OnGet: func() (interface{}, error) { return GoSNMPServer.Asn1IntegerWrap(runtime.NumGoroutine()), nil }, Document: "goroutineCount", }, } // Combine with built-in MIBs allOIDs := append(mibImps.All(), customOIDs...) master := GoSNMPServer.MasterAgent{ Logger: logger, SecurityConfig: GoSNMPServer.SecurityConfig{ AuthoritativeEngineBoots: 1, Users: []gosnmp.UsmSecurityParameters{ { UserName: "monitor", AuthenticationProtocol: gosnmp.SHA, PrivacyProtocol: gosnmp.AES, AuthenticationPassphrase: "monitorauth", PrivacyPassphrase: "monitorpriv", }, }, }, SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{"public"}, OIDs: allOIDs, }, }, } server := GoSNMPServer.NewSNMPServer(master) if err := server.ListenUDP("udp", "0.0.0.0:1161"); err != nil { log.Fatalf("Listen failed: %v", err) } // Graceful shutdown on SIGINT/SIGTERM sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigChan log.Println("Shutting down...") server.Shutdown() }() log.Println("SNMP server running on :1161") server.ServeForever() } var startTime = time.Now() ``` -------------------------------- ### Initialize MasterAgent Source: https://context7.com/slayercat/gosnmpserver/llms.txt Configures the top-level MasterAgent with security settings, SNMPv3 users, and SubAgent associations. Only one MasterAgent should be instantiated per server. ```go import ( "github.com/gosnmp/gosnmp" "github.com/slayercat/GoSNMPServer" ) master := GoSNMPServer.MasterAgent{ // Logger for server operations Logger: GoSNMPServer.NewDefaultLogger(), SecurityConfig: GoSNMPServer.SecurityConfig{ // Set to true to disable authentication NoSecurity: false, // Set to true to reject SNMPv1/v2c requests SnmpV3Only: false, // SNMPv3 engine boots counter (increment on restart) AuthoritativeEngineBoots: 1, // SNMPv3 users with auth/privacy settings Users: []gosnmp.UsmSecurityParameters{ { UserName: "admin", AuthenticationProtocol: gosnmp.SHA, PrivacyProtocol: gosnmp.AES, AuthenticationPassphrase: "authpass123", PrivacyPassphrase: "privpass123", }, { UserName: "readonly", AuthenticationProtocol: gosnmp.MD5, PrivacyProtocol: gosnmp.DES, AuthenticationPassphrase: "readauth", PrivacyPassphrase: "readpriv", }, }, }, // SubAgents handle different communities SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{"public", "private"}, OIDs: customOIDs, }, }, } ``` -------------------------------- ### ASN.1 IPAddress Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Demonstrates wrapping a net.IP into ASN.1 IPAddress format and unwrapping it. Used for IP address data in SNMP. ```go import "net" ip := net.ParseIP("192.168.1.1") val = GoSNMPServer.Asn1IPAddressWrap(ip) addr := GoSNMPServer.Asn1IPAddressUnwrap(val) ``` -------------------------------- ### Implement Built-in MIBs Source: https://context7.com/slayercat/gosnmpserver/llms.txt Utilize pre-built MIB implementations for system metrics or combine them with custom OIDs in a SubAgent. ```go import ( "github.com/slayercat/GoSNMPServer" "github.com/slayercat/GoSNMPServer/mibImps" "github.com/slayercat/GoSNMPServer/mibImps/ucdMib" "github.com/slayercat/GoSNMPServer/mibImps/ifMib" "github.com/slayercat/GoSNMPServer/mibImps/dismanEventMib" ) // Use all built-in MIBs (ucdMib + ifMib + dismanEventMib) allOIDs := mibImps.All() // Or use specific MIBs: // UCD-MIB: Memory, CPU, Load, Disk usage ucdOIDs := ucdMib.All() // IF-MIB: Network interface statistics ifOIDs := ifMib.All() // DISMAN-EVENT-MIB: Event management dismanOIDs := dismanEventMib.All() // Configure logging for MIBs logger := GoSNMPServer.NewDefaultLogger() mibImps.SetupLogger(logger) // Combine built-in and custom OIDs customOIDs := []*GoSNMPServer.PDUValueControlItem{ // your custom OIDs } subAgent := &GoSNMPServer.SubAgent{ CommunityIDs: []string{"public"}, OIDs: append(mibImps.All(), customOIDs...), } ``` -------------------------------- ### Import GoSNMPServer Packages Source: https://github.com/slayercat/gosnmpserver/blob/master/README.md Imports necessary packages for using the GoSNMPServer library, including the core library, gosnmp, and mibImps. ```golang import "github.com/gosnmp/gosnmp" import "github.com/slayercat/GoSNMPServer" import "github.com/slayercat/GoSNMPServer/mibImps" ``` -------------------------------- ### ASN.1 OctetString Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Shows how to wrap a Go string into an ASN.1 OctetString and unwrap it. Essential for string-based SNMP data. ```go val = GoSNMPServer.Asn1OctetStringWrap("hello") s := GoSNMPServer.Asn1OctetStringUnwrap(val) // s = "hello" ``` -------------------------------- ### ASN.1 OpaqueFloat Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Demonstrates wrapping a float32 into ASN.1 Opaque and unwrapping it. Used for opaque floating-point data. ```go val = GoSNMPServer.Asn1OpaqueFloatWrap(float32(3.14)) f32 := GoSNMPServer.Asn1OpaqueFloatUnwrap(val) ``` -------------------------------- ### ASN.1 Uinteger32 Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Illustrates wrapping a uint32 into ASN.1 Uinteger32 and unwrapping it. Used for unsigned 32-bit integers in SNMP. ```go val = GoSNMPServer.Asn1Uinteger32Wrap(uint32(12345)) u32 := GoSNMPServer.Asn1Uinteger32Unwrap(val) ``` -------------------------------- ### ASN.1 Integer Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Demonstrates wrapping a Go int to an ASN.1 Integer and unwrapping it back. Used for integer-based SNMP data types. ```go import "github.com/slayercat/GoSNMPServer" // Integer (int) val := GoSNMPServer.Asn1IntegerWrap(42) i := GoSNMPServer.Asn1IntegerUnwrap(val) // i = 42 ``` -------------------------------- ### Gracefully Shutdown Server Source: https://context7.com/slayercat/gosnmpserver/llms.txt Stops the server and releases the bound UDP listener. ```go server := GoSNMPServer.NewSNMPServer(master) server.ListenUDP("udp", "127.0.0.1:1161") // Run server in a goroutine go server.ServeForever() // Later, gracefully shutdown server.Shutdown() ``` -------------------------------- ### NewSNMPServer Source: https://context7.com/slayercat/gosnmpserver/llms.txt Creates a new SNMP server instance from a configured MasterAgent. The function validates the MasterAgent configuration and panics if validation fails. ```APIDOC ## NewSNMPServer Creates a new SNMP server instance from a configured MasterAgent. The function validates the MasterAgent configuration and panics if validation fails. ```go import "github.com/slayercat/GoSNMPServer" master := GoSNMPServer.MasterAgent{ Logger: GoSNMPServer.NewDefaultLogger(), SecurityConfig: GoSNMPServer.SecurityConfig{ AuthoritativeEngineBoots: 1, }, SubAgents: []*GoSNMPServer.SubAgent{ { CommunityIDs: []string{"public"}, OIDs: []*GoSNMPServer.PDUValueControlItem{}, }, }, } server := GoSNMPServer.NewSNMPServer(master) ``` ``` -------------------------------- ### ASN.1 Counter64 Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Shows wrapping a uint64 into ASN.1 Counter64 and unwrapping it. Used for 64-bit SNMP counters. ```go val = GoSNMPServer.Asn1Counter64Wrap(uint64(9999999999)) c64 := GoSNMPServer.Asn1Counter64Unwrap(val) ``` -------------------------------- ### ASN.1 Gauge32 Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Illustrates wrapping a uint into ASN.1 Gauge32 and unwrapping it. Used for 32-bit SNMP gauges. ```go val = GoSNMPServer.Asn1Gauge32Wrap(uint(500)) g32 := GoSNMPServer.Asn1Gauge32Unwrap(val) ``` -------------------------------- ### Define Custom Read-Write Integer OID Source: https://context7.com/slayercat/gosnmpserver/llms.txt Create a read-write integer OID that maintains state. The OnGet callback returns the current value, and OnSet updates it. ```go var currentValue int = 100 readWriteInt := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.1.3", Type: gosnmp.Integer, OnGet: func() (interface{}, error) { return GoSNMPServer.Asn1IntegerWrap(currentValue), nil }, OnSet: func(value interface{}) error { currentValue = GoSNMPServer.Asn1IntegerUnwrap(value) return nil }, Document: "myWritableInteger", } ``` -------------------------------- ### Handle SNMP Traps with OnTrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Use the OnTrap callback to process incoming SNMP Traps and InformRequests. InformRequests require a return value, while regular traps can return nil. ```go trapHandler := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.2.1", Type: gosnmp.OctetString, OnTrap: func(isInform bool, trapdata gosnmp.SnmpPDU) (interface{}, error) { if isInform { // InformRequest - response will be sent back log.Printf("Received Inform: OID=%s Value=%v", trapdata.Name, trapdata.Value) return GoSNMPServer.Asn1OctetStringWrap("acknowledged"), nil } // Regular Trap - response is silently discarded log.Printf("Received Trap: OID=%s Value=%v", trapdata.Name, trapdata.Value) return nil, nil }, Document: "trapReceiver", } ``` -------------------------------- ### ASN.1 TimeTicks Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Demonstrates wrapping a uint32 into ASN.1 TimeTicks and unwrapping it. Used for time-related SNMP values. ```go val = GoSNMPServer.Asn1TimeTicksWrap(uint32(123456)) ticks := GoSNMPServer.Asn1TimeTicksUnwrap(val) ``` -------------------------------- ### ASN.1 Counter32 Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Shows wrapping a uint into ASN.1 Counter32 and unwrapping it. Used for 32-bit SNMP counters. ```go val = GoSNMPServer.Asn1Counter32Wrap(uint(1000)) c32 := GoSNMPServer.Asn1Counter32Unwrap(val) ``` -------------------------------- ### Initialize SubAgent Source: https://context7.com/slayercat/gosnmpserver/llms.txt Defines a SubAgent to handle specific SNMP communities and OID mappings. UserErrorMarkPacket determines if callback errors result in GenErr responses. ```go subAgent := &GoSNMPServer.SubAgent{ // List of community strings this agent responds to // For SNMPv3, this matches the ContextName CommunityIDs: []string{"public", "monitoring"}, // OID handlers for this agent OIDs: []*GoSNMPServer.PDUValueControlItem{ // ... OID definitions }, // If true, user errors in callbacks return GenErr in SNMP response UserErrorMarkPacket: true, // Logger (automatically set from MasterAgent) Logger: GoSNMPServer.NewDefaultLogger(), } ``` -------------------------------- ### ASN.1 OpaqueDouble Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Shows wrapping a float64 into ASN.1 Opaque and unwrapping it. Used for opaque double-precision floating-point data. ```go val = GoSNMPServer.Asn1OpaqueDoubleWrap(float64(3.14159265359)) f64 := GoSNMPServer.Asn1OpaqueDoubleUnwrap(val) ``` -------------------------------- ### Define OID with Permission Checking Source: https://context7.com/slayercat/gosnmpserver/llms.txt Implement an OID with custom permission checks. The OnCheckPermission callback restricts access based on SNMP version and context name. ```go restricted := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.1.6", Type: gosnmp.OctetString, OnCheckPermission: func( pktVersion gosnmp.SnmpVersion, pduType gosnmp.PDUType, contextName string, ) GoSNMPServer.PermissionAllowance { // Only allow SNMPv3 access if pktVersion != gosnmp.Version3 { return GoSNMPServer.PermissionAllowanceDenied } // Only allow "admin" community/context if contextName != "admin" { return GoSNMPServer.PermissionAllowanceDenied } return GoSNMPServer.PermissionAllowanceAllowed }, OnGet: func() (interface{}, error) { return GoSNMPServer.Asn1OctetStringWrap("secret data"), nil }, Document: "restrictedData", } ``` -------------------------------- ### ASN.1 ObjectIdentifier Wrap and Unwrap Source: https://context7.com/slayercat/gosnmpserver/llms.txt Illustrates wrapping a string OID into ASN.1 ObjectIdentifier format and unwrapping it. Used for representing OIDs in SNMP. ```go val = GoSNMPServer.Asn1ObjectIdentifierWrap("1.3.6.1.2.1.1.1") oid := GoSNMPServer.Asn1ObjectIdentifierUnwrap(val) ``` -------------------------------- ### ListenUDP Source: https://context7.com/slayercat/gosnmpserver/llms.txt Binds the SNMP server to a UDP address. The l3proto parameter specifies the network type ("udp", "udp4", or "udp6"), and address specifies the host:port to listen on. ```APIDOC ## ListenUDP Binds the SNMP server to a UDP address. The l3proto parameter specifies the network type ("udp", "udp4", or "udp6"), and address specifies the host:port to listen on. ```go server := GoSNMPServer.NewSNMPServer(master) // Listen on all interfaces, port 161 (standard SNMP port) err := server.ListenUDP("udp", "0.0.0.0:161") if err != nil { log.Fatalf("Failed to listen: %v", err) } // Or listen on localhost only, non-privileged port err = server.ListenUDP("udp", "127.0.0.1:1161") // IPv6 support err = server.ListenUDP("udp6", "::1":1161) ``` ``` -------------------------------- ### Validate OID Strings Source: https://context7.com/slayercat/gosnmpserver/llms.txt Check if an OID string is valid using VerifyOid before registration. ```go import "github.com/slayercat/GoSNMPServer" // Valid OIDs err := GoSNMPServer.VerifyOid("1.3.6.1.2.1.1.1") if err != nil { log.Printf("Invalid OID: %v", err) } // With leading dot (also valid) err = GoSNMPServer.VerifyOid(".1.3.6.1.2.1.1.1") // Invalid OIDs will return error err = GoSNMPServer.VerifyOid("1.3.6.1.abc.1") // non-numeric err = GoSNMPServer.VerifyOid("1.3..6.1") // empty segment err = GoSNMPServer.VerifyOid("") // empty string ``` -------------------------------- ### Define Custom Read-Only Integer OID Source: https://context7.com/slayercat/gosnmpserver/llms.txt Create a read-only integer OID handler. The OnGet callback returns a static integer value wrapped as an ASN.1 Integer. ```go import ( "fmt" "github.com/gosnmp/gosnmp" "github.com/slayercat/GoSNMPServer" ) // Simple read-only integer OID readOnlyInt := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.1.1", Type: gosnmp.Integer, OnGet: func() (interface{}, error) { return GoSNMPServer.Asn1IntegerWrap(42), nil }, Document: "myCustomInteger", } ``` -------------------------------- ### Define Custom Counter OID Source: https://context7.com/slayercat/gosnmpserver/llms.txt Implement a Counter32 OID that dynamically reports a count. The OnGet callback fetches the current request count. ```go counter := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.1.4", Type: gosnmp.Counter32, OnGet: func() (interface{}, error) { // Read actual counter from system count := getRequestCount() return GoSNMPServer.Asn1Counter32Wrap(uint(count)), nil }, Document: "requestCounter", } ``` -------------------------------- ### Bind Server to UDP Address Source: https://context7.com/slayercat/gosnmpserver/llms.txt Configures the network protocol and address for the SNMP server. Supports IPv4 and IPv6 addresses. ```go server := GoSNMPServer.NewSNMPServer(master) // Listen on all interfaces, port 161 (standard SNMP port) err := server.ListenUDP("udp", "0.0.0.0:161") if err != nil { log.Fatalf("Failed to listen: %v", err) } // Or listen on localhost only, non-privileged port err = server.ListenUDP("udp", "127.0.0.1:1161") // IPv6 support err = server.ListenUDP("udp6", "[::1]:1161") ``` -------------------------------- ### Define Non-Walkable Write-Only OID Source: https://context7.com/slayercat/gosnmpserver/llms.txt Configure a write-only OID that is not included in WALK operations. The OnSet callback executes a command based on the received value. ```go writeOnly := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.1.5", Type: gosnmp.OctetString, NonWalkable: true, OnSet: func(value interface{}) error { command := GoSNMPServer.Asn1OctetStringUnwrap(value) return executeCommand(command) }, Document: "commandInput", } ``` -------------------------------- ### Shutdown Source: https://context7.com/slayercat/gosnmpserver/llms.txt Gracefully stops the SNMP server and releases the UDP listener. ```APIDOC ## Shutdown Gracefully stops the SNMP server and releases the UDP listener. ```go server := GoSNMPServer.NewSNMPServer(master) server.ListenUDP("udp", "127.0.0.1:1161") // Run server in a goroutine go server.ServeForever() // Later, gracefully shutdown server.Shutdown() ``` ``` -------------------------------- ### Define Custom Read-Only String OID Source: https://context7.com/slayercat/gosnmpserver/llms.txt Implement a read-only OctetString OID handler. The OnGet callback provides a string value, wrapped for ASN.1 OctetString. ```go readOnlyString := &GoSNMPServer.PDUValueControlItem{ OID: "1.3.6.1.4.1.12345.1.2", Type: gosnmp.OctetString, OnGet: func() (interface{}, error) { return GoSNMPServer.Asn1OctetStringWrap("Hello SNMP"), nil }, Document: "myCustomString", } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.