//go:build linux package checker import ( "bytes" "context" "encoding/binary" "errors" "fmt" "net" "sync/atomic" "syscall" "time" ) var icmpIDCounter uint32 func nativeICMPPing(ctx context.Context, host string, count int, timeout time.Duration, privilegedOnly bool) (float64, error) { if count <= 0 { count = 1 } ips, err := net.DefaultResolver.LookupIP(ctx, "ip4", host) if err != nil || len(ips) == 0 { return 0, fmt.Errorf("resolve %s: %w", host, err) } ip4 := ips[0].To4() if ip4 == nil { return 0, fmt.Errorf("no IPv4 address for %s", host) } // Try Linux unprivileged ICMP datagram socket (SOCK_DGRAM + IPPROTO_ICMP) first unless privilegedOnly is set, // with fallback to raw ICMP socket (SOCK_RAW + IPPROTO_ICMP). sockTypes := []int{syscall.SOCK_DGRAM, syscall.SOCK_RAW} if privilegedOnly { sockTypes = []int{syscall.SOCK_RAW, syscall.SOCK_DGRAM} } fd := -1 usedType := 0 for _, st := range sockTypes { s, sockErr := syscall.Socket(syscall.AF_INET, st, syscall.IPPROTO_ICMP) if sockErr == nil { fd = s usedType = st break } } if fd < 0 { return 0, errICMPUnavailable } defer syscall.Close(fd) id := uint16(atomic.AddUint32(&icmpIDCounter, 1) & 0xffff) if id == 0 { id = uint16(atomic.AddUint32(&icmpIDCounter, 1) & 0xffff) } var sa syscall.SockaddrInet4 copy(sa.Addr[:], ip4) overallDeadline := time.Now().Add(timeout) buf := make([]byte, 1500) var rttSum float64 var received int var lastErr error for seq := 1; seq <= count; seq++ { if ctx.Err() != nil { if received > 0 { break } return 0, ctx.Err() } remainingTotal := time.Until(overallDeadline) if remainingTotal <= 0 { break } pktsLeft := count - seq + 1 pktTimeout := remainingTotal / time.Duration(pktsLeft) if pktTimeout < 50*time.Millisecond && remainingTotal > 50*time.Millisecond { pktTimeout = 50 * time.Millisecond } pktDeadline := time.Now().Add(pktTimeout) if pktDeadline.After(overallDeadline) { pktDeadline = overallDeadline } // Construct ICMPv4 Echo Request (type 8, code 0) pkt := make([]byte, 16) pkt[0] = 8 // Echo Request pkt[1] = 0 binary.BigEndian.PutUint16(pkt[4:6], id) binary.BigEndian.PutUint16(pkt[6:8], uint16(seq)) copy(pkt[8:], []byte("RUD-PING")) cs := icmpChecksum(pkt) binary.BigEndian.PutUint16(pkt[2:4], cs) sendTV := syscall.NsecToTimeval(pktTimeout.Nanoseconds()) _ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &sendTV) sendStart := time.Now() if err := syscall.Sendto(fd, pkt, 0, &sa); err != nil { lastErr = err continue } for { if ctx.Err() != nil { if received > 0 { return rttSum / float64(received), nil } return 0, ctx.Err() } rem := time.Until(pktDeadline) if rem <= 0 { lastErr = errors.New("icmp echo timeout") break } slice := rem if slice > 200*time.Millisecond { slice = 200 * time.Millisecond } rcvTV := syscall.NsecToTimeval(slice.Nanoseconds()) _ = syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &rcvTV) n, from, rcvErr := syscall.Recvfrom(fd, buf, 0) if rcvErr != nil { if errors.Is(rcvErr, syscall.EINTR) || errors.Is(rcvErr, syscall.EAGAIN) || errors.Is(rcvErr, syscall.EWOULDBLOCK) { continue } lastErr = rcvErr break } if n < 8 { continue } if from4, ok := from.(*syscall.SockaddrInet4); !ok || !bytes.Equal(from4.Addr[:], ip4) { continue } payload := buf[:n] if usedType == syscall.SOCK_RAW && len(payload) >= 20 && (payload[0]>>4) == 4 { hdrLen := int(payload[0]&0x0f) * 4 if hdrLen < 20 || len(payload) < hdrLen+8 { continue } payload = payload[hdrLen:] } // Ignore non-Echo-Reply packets (e.g. Echo Requests seen on loopback SOCK_RAW) if payload[0] != 0 || payload[1] != 0 { continue } replyID := binary.BigEndian.Uint16(payload[4:6]) replySeq := binary.BigEndian.Uint16(payload[6:8]) if usedType == syscall.SOCK_RAW && replyID != id { continue } if replySeq != uint16(seq) { continue } rttMs := float64(time.Since(sendStart).Microseconds()) / 1000.0 rttSum += rttMs received++ break } } if received > 0 { return rttSum / float64(received), nil } if lastErr == nil { lastErr = errors.New("icmp echo timeout") } return 0, lastErr } func icmpChecksum(b []byte) uint16 { var sum uint32 for i := 0; i < len(b)-1; i += 2 { sum += uint32(binary.BigEndian.Uint16(b[i : i+2])) } if len(b)%2 == 1 { sum += uint32(b[len(b)-1]) << 8 } for (sum >> 16) > 0 { sum = (sum & 0xffff) + (sum >> 16) } return ^uint16(sum) }