Skip to content

Instantly share code, notes, and snippets.

@mattn
Created December 19, 2014 06:01
Show Gist options
  • Save mattn/7ff153fe8491a2900e83 to your computer and use it in GitHub Desktop.
Save mattn/7ff153fe8491a2900e83 to your computer and use it in GitHub Desktop.
func TestPingGoogle(t *testing.T) {
if testing.Short() {
t.Skip("to avoid external network")
}
switch runtime.GOOS {
case "darwin":
case "linux":
t.Log("you may need to adjust the net.ipv4.ping_group_range kernel state")
default:
t.Skipf("not supported on %q", runtime.GOOS)
}
for i, tt := range pingGoogleTests {
if tt.network[:2] == "ip" && os.Getuid() != 0 {
continue
}
c, err := icmp.ListenPacket(tt.network, tt.address)
if err != nil {
t.Error(err)
continue
}
defer c.Close()
// MODIFIED BEGIN
if err := c.IPv4PacketConn().SetTTL(1); err != nil {
t.Fatal(err)
}
// MODIFIED END
dst, err := googleAddr(c, tt.protocol)
if err != nil {
t.Error(err)
continue
}
wm := icmp.Message{
Type: tt.mtype, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, Seq: 1 << uint(i),
Data: []byte("HELLO-R-U-THERE"),
},
}
wb, err := wm.Marshal(nil)
if err != nil {
t.Error(err)
continue
}
if n, err := c.WriteTo(wb, dst); err != nil {
t.Error(err, dst)
continue
} else if n != len(wb) {
t.Errorf("got %v; want %v", n, len(wb))
continue
}
rb := make([]byte, 1500)
n, peer, err := c.ReadFrom(rb)
if err != nil {
t.Error(err)
continue
}
rm, err := icmp.ParseMessage(tt.protocol, rb[:n])
if err != nil {
t.Error(err)
continue
}
switch rm.Type {
case ipv4.ICMPTypeEchoReply, ipv6.ICMPTypeEchoReply:
t.Logf("got reflection from %v", peer)
default:
t.Errorf("got %+v; want echo reply", rm)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment