{"modulePath":"github.com/randomizedcoder/icmpengine","version":"v1.2.0","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package icmpengine\n\nPackage icmpengine sends non-privileged ICMP echo requests and receives the replies concurrently, without blocking on per-packet timeouts. It is designed to be embedded in other Go programs.\n\nNon-privileged ICMP uses IPPROTO\\_ICMP sockets (see [https://lwn.net/Articles/422330/](https://lwn.net/Articles/422330/)). On Linux this requires the ping group range sysctl to include the running user's gid, e.g.:\n\n\tsudo sysctl -w net.ipv4.ping_group_range=\"0 2147483647\"\n\nTypical use:\n\n\teng, err := icmpengine.New(icmpengine.WithLogger(logger))\n\tif err != nil { ... }\n\tif err := eng.Start(ctx); err != nil { ... }\n\tdefer eng.Close()\n\tres, err := eng.Ping(ctx, netip.MustParseAddr(\"8.8.8.8\"), 10, 100*time.Millisecond)\n\n## Constants\n\n```go\nconst IsRaceEnabled = false\n```\nIsRaceEnabled reports if the race detector is enabled.\n\n## Variables\n\n```go\nvar (\n\t// ErrNotStarted is returned by Ping when the engine has not been Started\n\t// (or has already been Closed).\n\tErrNotStarted = errors.New(\"icmpengine: engine not started\")\n\t// ErrAlreadyStarted is returned by Start when called more than once.\n\tErrAlreadyStarted = errors.New(\"icmpengine: engine already started\")\n\t// ErrCountRange is returned by Ping when count is outside [0, 65535]\n\t// (ICMP sequence numbers are 16 bits).\n\tErrCountRange = errors.New(\"icmpengine: count out of range [0,65535]\")\n\t// ErrDuplicatePing is returned by Ping when another Ping to the same\n\t// address is already in flight on this engine.\n\tErrDuplicatePing = errors.New(\"icmpengine: address already being pinged\")\n\t// ErrInvalidAddr is returned by Ping when the destination address is not\n\t// a valid IPv4 or IPv6 address.\n\tErrInvalidAddr = errors.New(\"icmpengine: invalid destination address\")\n\t// ErrTimeoutRange is returned by Ping when a PingTimeout value is negative.\n\tErrTimeoutRange = errors.New(\"icmpengine: ping timeout must be \u003e= 0\")\n\t// ErrPayloadSizeRange is returned by Ping when a PayloadSize value is\n\t// outside [0, maxPayloadSize].\n\tErrPayloadSizeRange = errors.New(\"icmpengine: payload size out of range [0,65500]\")\n\t// ErrDSCPRange is returned by Ping when a DSCP value is outside [0, 63].\n\tErrDSCPRange = errors.New(\"icmpengine: dscp out of range [0,63]\")\n\t// ErrTTLRange is returned by New when a WithTTL value is outside [0, 255]\n\t// (0 means keep the kernel default).\n\tErrTTLRange = errors.New(\"icmpengine: ttl out of range [0,255]\")\n\t// ErrDontFragmentUnsupported is returned by Start when WithDontFragment was\n\t// set on a platform where the engine cannot set it on non-privileged sockets\n\t// (everything except Linux).\n\tErrDontFragmentUnsupported = errors.New(\"icmpengine: dont fragment is only supported on linux\")\n)\n```\nSentinel errors returned by the engine.\n\n## Types\n\n```go\ntype Backend int\n```\nBackend selects the expiry-tracking data structure used by an Engine.\n\n```go\nconst (\n\t// BackendHeap uses container/heap, a binary min-heap. Peek is O(1); push and\n\t// remove are O(log n). No external dependency.\n\tBackendHeap Backend = iota\n\t// BackendBTree uses github.com/google/btree. All operations are O(log n).\n\tBackendBTree\n\t// BackendDaryHeap uses an 8-ary array heap — shallower than the binary heap,\n\t// which benchmarks fastest on this remove-heavy workload (see BenchmarkDaryFanout).\n\t// It is the default: New with no WithExpiryBackend uses it.\n\tBackendDaryHeap\n\t// BackendRadix uses a fixed-base MSD radix trie over the 64-bit expiry key;\n\t// all operations are O(64/8)=O(8), independent of n.\n\tBackendRadix\n\t// BackendPairing uses a pairing heap (O(1) push/peek).\n\tBackendPairing\n\t// BackendTimingWheel uses a hierarchical absolute-time timing wheel with a\n\t// btree overflow. Best under near-monotonic load; see expiry_wheel.go.\n\tBackendTimingWheel\n)\n```\n\n```go\nfunc (b Backend) String() string\n```\nString implements fmt.Stringer for nicer logging and flag handling.\n\n```go\ntype Engine struct {\n\t// contains filtered or unexported fields\n}\n```\nEngine sends ICMP echo requests and matches them to replies. Create one with New, Start it, call Ping/PingAll, then Close it. An Engine is safe for concurrent use by multiple goroutines. It implements io.Closer.\n\n```go\nfunc New(opts ...Option) (*Engine, error)\n```\nNew creates an Engine from the given options. It validates configuration and returns an error instead of terminating the process. New does not open sockets or start goroutines; call Start for that.\n\n```go\nfunc (e *Engine) Close() error\n```\nClose shuts the engine down: it cancels the engine context, waits for all in-flight pings and background goroutines to finish, and closes the sockets. Close is idempotent and returns the first fatal background error, if any.\n\n```go\nfunc (e *Engine) Err() error\n```\nErr returns the first fatal error observed by a background (receiver) goroutine, or nil. A non-nil Err means the engine has begun shutting itself down.\n\n```go\nfunc (e *Engine) Ping(ctx context.Context, addr netip.Addr, count int, interval time.Duration, opts ...PingOption) (Result, error)\n```\nPing sends count echo requests to addr, interval apart, and returns aggregated statistics. It blocks until every packet has been answered or timed out, or until ctx (or the engine) is canceled. On cancellation it returns the partial Result gathered so far alongside a non-nil error.\n\n```go\nfunc (e *Engine) PingAll(ctx context.Context, concurrency int, targets []Target) ([]Result, error)\n```\nPingAll pings every target concurrently with at most concurrency pings in flight at once (concurrency \\\u003c= 0 means one worker per target). Results are returned aligned to targets. It returns the first error encountered, if any; per-target partial results are still populated.\n\n```go\nfunc (e *Engine) Start(ctx context.Context) error\n```\nStart opens the ICMP sockets and launches the receiver goroutines. The provided context governs the engine's lifetime: canceling it (or calling Close) shuts everything down. Start may be called only once.\n\n```go\ntype ICMPEchoReply struct {\n\tType       uint8\n\tCode       uint8\n\tChecksum   uint16\n\tIdentifier uint16\n\tSeq        uint16\n}\n```\nICMPEchoReply represents Echo Reply messages per the IPv4/rfc792 and IPv6/rfc2463 ( see extended comments below )\n\n```go\nfunc ParseICMPEchoReply(b []byte) (*ICMPEchoReply, error)\n```\nParseICMPEchoReply parses the ICMP echo reply messages This was originally based on on the the golang standard icmp ParseMessage, which for unknown reasons don't parse ICMP echo [https://pkg.go.dev/golang.org/x/net/icmp#ParseMessage](https://pkg.go.dev/golang.org/x/net/icmp#ParseMessage) [https://github.com/golang/net/blob/7fd8e65b6420/icmp/message.go#L139](https://github.com/golang/net/blob/7fd8e65b6420/icmp/message.go#L139)\n\n```go\nfunc ParseICMPEchoReplyBB(b bytes.Buffer) (*ICMPEchoReply, error)\n```\nParseICMPEchoReplyBB is the same as ParseICMPEchoReply, except uses bytes.Buffer, instead of \\[]byte This is mostly to allow use of sync.Pool, which should be faster (maybe?) [https://www.akshaydeo.com/blog/2017/12/23/How-did-I-improve-latency-by-700-percent-using-syncPool/](https://www.akshaydeo.com/blog/2017/12/23/How-did-I-improve-latency-by-700-percent-using-syncPool/)\n\n```go\ntype Option func(*config)\n```\nOption configures an Engine created by New.\n\n```go\nfunc WithDSCP(v int) Option\n```\nWithDSCP marks every echo request sent by this engine with the given 6-bit DiffServ code point (0-63). It is written into the IPv4 ToS / IPv6 Traffic Class byte as v\\\u003c\\\u003c2 (the low two ECN bits stay zero) and applied once, at Start, to both the IPv4 and IPv6 socket. It is engine-wide rather than per-ping because the engine shares one socket per family across all concurrent pings. Defaults to 0 (unmarked). Values outside \\[0, 63] are rejected by New.\n\n```go\nfunc WithDontFragment(b bool) Option\n```\nWithDontFragment sets the IPv4 Don't-Fragment bit (and the IPv6 equivalent) on outgoing echo requests by enabling path-MTU discovery on the socket (IP\\_MTU\\_DISCOVER / IPV6\\_MTU\\_DISCOVER = DO). Combined with WithPayloadSize it lets a caller probe the path MTU without privileged raw sockets. It is applied at Start; on platforms other than Linux, Start returns ErrDontFragmentUnsupported. Defaults to false.\n\n```go\nfunc WithExpiryBackend(b Backend) Option\n```\nWithExpiryBackend selects the data structure used to track outstanding pings. Defaults to BackendDaryHeap (the fastest in benchmarks); see docs/backends.md.\n\n```go\nfunc WithFakeSuccess(b bool) Option\n```\nWithFakeSuccess makes the engine synthesize successful replies without opening sockets or sending packets. Intended for testing only.\n\n```go\nfunc WithHackSysctl(b bool) Option\n```\nWithHackSysctl allows the engine, when running as root, to run \"sysctl -w net.ipv4.ping\\_group\\_range=0 2147483647\" if opening sockets fails. Off by default; opt in only if you understand the implication.\n\n```go\nfunc WithLogger(l *slog.Logger) Option\n```\nWithLogger sets the structured logger. A nil logger (the default) discards all log output.\n\n```go\nfunc WithReadDeadline(d time.Duration) Option\n```\nWithReadDeadline sets the receiver socket read deadline. It bounds how quickly receivers notice Close/cancellation; it is not a per-ping timeout. Defaults to 1s.\n\n```go\nfunc WithReceivers(v4, v6 int) Option\n```\nWithReceivers sets the number of receiver goroutines per protocol. Defaults to 2 and 2.\n\n```go\nfunc WithSource(addr netip.Addr) Option\n```\nWithSource binds the engine's sockets to a specific source address, so echo requests leave from that address (useful on multi-homed hosts). The address applies to its own family only: an IPv4 source binds the IPv4 socket and leaves the IPv6 socket on its default (and vice versa). A zero Addr (the default) binds to the wildcard address. Binding is done at Start; an address that is not a local address makes Start fail.\n\n```go\nfunc WithSplayReceivers(b bool) Option\n```\nWithSplayReceivers staggers receiver startup over the read deadline instead of starting them all at once. Defaults to false.\n\n```go\nfunc WithTTL(n int) Option\n```\nWithTTL sets the outgoing IPv4 TTL (and the equivalent IPv6 hop limit) for every echo request sent by this engine. It is applied once, at Start, to both sockets — engine-wide rather than per-ping for the same reason as WithDSCP. Defaults to 64 (the Linux ping / kernel default); a value of 0 keeps the kernel default without setting the option. Values outside \\[0, 255] are rejected by New.\n\n```go\nfunc WithTimeout(d time.Duration) Option\n```\nWithTimeout sets how long to wait for an echo reply before a ping is counted as a failure. Defaults to 1s.\n\n```go\ntype PingOption func(*pingConfig)\n```\nPingOption customizes a single Ping call.\n\n```go\nfunc DropProbability(p float64) PingOption\n```\nDropProbability fakes packet loss with the given probability in \\[0,1] by not actually sending the echo request. Intended for testing only.\n\n```go\nfunc PayloadSize(n int) PingOption\n```\nPayloadSize sets the number of ICMP data bytes appended after the 8-byte ICMP header, like ping's -s option (so PayloadSize(56) yields a 64-byte ICMP message). The kernel adds the IP header on top. A value of 0 (the default) sends a bare echo request. Values outside \\[0, 65500] are rejected by Ping.\n\n```go\nfunc PingTimeout(d time.Duration) PingOption\n```\nPingTimeout overrides the engine's default timeout for this Ping call, so different destinations can wait different amounts of time before a packet is counted as a failure (e.g. 10ms on a LAN, hours for an interplanetary link). A zero value keeps the engine default; a negative value is rejected.\n\n```go\nfunc SortRTTs() PingOption\n```\nSortRTTs sorts Result.RTTs ascending before returning.\n\n```go\ntype Result struct {\n\tIP         netip.Addr\n\tSuccesses  int\n\tFailures   int\n\tOutOfOrder int\n\tRTTs       []time.Duration\n\tCount      int\n\tMin        time.Duration\n\tMax        time.Duration\n\tMean       time.Duration\n\tVariance   time.Duration\n\tSum        time.Duration\n\t// Duration is the wall-clock time the Ping call took.\n\tDuration time.Duration\n}\n```\nResult holds the aggregated statistics for a single Ping call.\n\n```go\ntype Target struct {\n\tAddr     netip.Addr\n\tCount    int\n\tInterval time.Duration\n\tOptions  []PingOption\n}\n```\nTarget describes one destination for PingAll.\n\n","path":"github.com/randomizedcoder/icmpengine","name":"icmpengine","synopsis":"Package icmpengine sends non-privileged ICMP echo requests and receives the replies concurrently, without blocking on per-packet timeouts.","isRedistributable":true}
