ping

package
v1.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2025 License: MIT Imports: 13 Imported by: 1

Documentation

Overview

Package ping sends and receives icmp echo request/reply packets over a UDP socket. Both IPv4 and IPv6 are supported.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTimeout = errors.New("timeout waiting for response")
)

Functions

This section is empty.

Types

type Request

type Request struct {
	TimeSent time.Time
	Target   net.IP
	Seq      SequenceNumber
	TTL      uint8
}

Request represents an icmp packet sent by the Socket.

type Response

type Response struct {
	From         net.IP
	Request      Request
	ResponseType ResponseType
	Latency      time.Duration
}

Response represents an icmp packet received by the Socket.

func (Response) LogValue

func (r Response) LogValue() slog.Value

type ResponseType

type ResponseType int
const (
	ResponseEchoReply ResponseType = iota
	ResponseTimeExceeded
	ResponseTimeout
)

func (ResponseType) String

func (rt ResponseType) String() string

type SequenceNumber

type SequenceNumber uint16

SequenceNumber represents the sequence number of an icmp packet.

type Socket

type Socket struct {
	Timeout time.Duration
	// contains filtered or unexported fields
}

func New

func New(opts ...SocketOption) (*Socket, error)

New creates a new Socket instance.

func (*Socket) Read

func (s *Socket) Read(ctx context.Context) (Response, error)

Read reads the next icmp packet from the socket. It blocks until a packet is received or the context is canceled.

func (*Socket) Resolve

func (s *Socket) Resolve(host string) (net.IP, error)

Resolve resolves the provided host to an IP address and returns it. Resolve returns an error if the host does not have a valid IP address of a type supported by the socket (e.g., if the socket only supports IPv6, but the host doesn't have an IPv4 address).

func (*Socket) Send

func (s *Socket) Send(target net.IP, seq SequenceNumber, ttl uint8, payload []byte) error

Send creates an icmp packet with the provided seq, ttl and payload and sends it to the specified target.

func (*Socket) Serve

func (s *Socket) Serve(ctx context.Context)

Serve listens for icmp packets on the socket and dispatches them to the appropriate handler. It's the responsibility of the caller to call Serve before sending or receiving packets. Serve blocks until the context is canceled.

type SocketOption

type SocketOption func(*Socket) error

func WithIPv4

func WithIPv4() SocketOption

func WithIPv6

func WithIPv6() SocketOption

func WithLogger

func WithLogger(l *slog.Logger) SocketOption

func WithTimeout

func WithTimeout(d time.Duration) SocketOption

func WithoutCheckID

func WithoutCheckID() SocketOption

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL