Implement the ping protocol in Go
By Kemi Adeyemi, Backend Track Lead
In the previous post we wrote ping in C with a raw socket. This time we build the same program in Go, using nothing but the standard library. The protocol is identical, so if you haven't read the C version, its first section explains ICMP echo and the Internet checksum in more detail.
The checksum and the message
An ICMP echo request is 8 bytes of header (type, code, checksum, identifier, sequence number) followed by any payload we like. We put the send time in the payload, in nanoseconds, so we can measure the round trip when the reply comes back. encoding/binary writes the multi-byte fields in network byte order, so there is no htons to forget.
// A minimal IPv4 ping using only Go's standard library.
// Run: go build -o ping . && sudo ./ping example.com
package main
import (
"encoding/binary"
"fmt"
"net"
"os"
"time"
)
const (
echoRequest = 8
echoReply = 0
payloadSize = 56
)
// checksum is the Internet checksum (RFC 1071).
func checksum(b []byte) uint16 {
var sum uint32
for i := 0; i+1 < len(b); i += 2 {
sum += uint32(b[i])<<8 | uint32(b[i+1])
}
if len(b)%2 == 1 {
sum += uint32(b[len(b)-1]) << 8
}
for sum>>16 != 0 {
sum = sum&0xffff + sum>>16
}
return ^uint16(sum)
}
// echoMessage builds an ICMP echo request with the send time in the payload.
func echoMessage(id, seq uint16, sent time.Time) []byte {
msg := make([]byte, 8+payloadSize)
msg[0] = echoRequest // type; code (msg[1]) stays 0
binary.BigEndian.PutUint16(msg[4:], id)
binary.BigEndian.PutUint16(msg[6:], seq)
binary.BigEndian.PutUint64(msg[8:], uint64(sent.UnixNano()))
binary.BigEndian.PutUint16(msg[2:], checksum(msg))
return msg
}Opening a raw ICMP socket
net.ListenPacket with the network "ip4:icmp" gives us a raw ICMP socket, the Go equivalent of socket(AF_INET, SOCK_RAW, IPPROTO_ICMP). Like the C version, it needs root or the CAP_NET_RAW capability. One nice difference: on reads, Go strips the IPv4 header for us, so the buffer starts at the ICMP message.
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "usage: %s host\n", os.Args[0])
os.Exit(2)
}
host := os.Args[1]
dst, err := net.ResolveIPAddr("ip4", host)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// "ip4:icmp" opens a raw ICMP socket (needs root or CAP_NET_RAW).
// On reads, Go strips the IPv4 header, so buf starts at the ICMP message.
conn, err := net.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
fmt.Fprintln(os.Stderr, "listen (run as root or grant CAP_NET_RAW):", err)
os.Exit(1)
}
defer conn.Close()
id := uint16(os.Getpid())
const count = 4
sent, received := 0, 0
fmt.Printf("PING %s (%s): %d data bytes\n", host, dst.IP, payloadSize)Send, then wait for our own reply
For each sequence number we send a request and read until our reply arrives or a one-second deadline passes. A raw socket receives every ICMP packet that reaches the machine, including other programs' pings and, on loopback, our own request, so we check the type, identifier and sequence number before trusting a packet.
for seq := uint16(1); seq <= count; seq++ {
if _, err := conn.WriteTo(echoMessage(id, seq, time.Now()), dst); err != nil {
fmt.Fprintln(os.Stderr, "write:", err)
break
}
sent++
deadline := time.Now().Add(time.Second)
conn.SetReadDeadline(deadline)
buf := make([]byte, 1500)
for {
n, peer, err := conn.ReadFrom(buf)
if err != nil { // deadline passed
fmt.Printf("Request timeout for icmp_seq %d\n", seq)
break
}
msg := buf[:n]
// A raw socket sees every ICMP packet for this host: keep only our reply.
if n < 16 || msg[0] != echoReply ||
binary.BigEndian.Uint16(msg[4:]) != id || binary.BigEndian.Uint16(msg[6:]) != seq {
continue
}
if checksum(msg) != 0 {
continue // corrupted
}
sentAt := time.Unix(0, int64(binary.BigEndian.Uint64(msg[8:])))
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%.3f ms\n",
n, peer, seq, float64(time.Since(sentAt).Microseconds())/1000)
received++
break
}
if seq < count {
time.Sleep(time.Second)
}
}
loss := 0.0
if sent > 0 {
loss = 100 * float64(sent-received) / float64(sent)
}
fmt.Printf("--- %s ping statistics ---\n%d packets transmitted, %d received, %.0f%% packet loss\n",
host, sent, received, loss)
if received == 0 {
os.Exit(1)
}
}Run it
$ go build -o ping . && sudo ./ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=1 time=0.074 ms
64 bytes from 127.0.0.1: icmp_seq=2 time=0.081 ms
64 bytes from 127.0.0.1: icmp_seq=3 time=0.180 ms
64 bytes from 127.0.0.1: icmp_seq=4 time=0.114 ms
--- 127.0.0.1 ping statistics ---
4 packets transmitted, 4 received, 0% packet lossInstead of sudo you can grant the capability once with sudo setcap cap_net_raw+ep ./ping.
Going further
- For production code, the golang.org/x/net/icmp package parses and marshals ICMP messages for you, supports IPv6, and can open unprivileged "udp4" ICMP sockets on Linux and macOS, so no root is needed.
- Send the next request on a timer instead of after each reply, so one slow reply doesn't delay the rest. A goroutine for reading and one for sending is a natural fit.
- Add min, average and maximum round-trip times to the summary, like the real ping.
Put this next to the C version and you can see what Go gives you: no manual byte-order conversion, no buffer arithmetic for the IP header, deadlines instead of socket options, and a static binary you can copy to any Linux box.