github.com/lianghucheng/zrddz@v0.0.0-20200923083010-c71f680932e2/src/golang.org/x/net/icmp/example_test.go (about) 1 // Copyright 2014 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package icmp_test 6 7 import ( 8 "log" 9 "net" 10 "os" 11 "runtime" 12 13 "golang.org/x/net/icmp" 14 "golang.org/x/net/ipv6" 15 ) 16 17 func ExamplePacketConn_nonPrivilegedPing() { 18 switch runtime.GOOS { 19 case "darwin": 20 case "linux": 21 log.Println("you may need to adjust the net.ipv4.ping_group_range kernel state") 22 default: 23 log.Println("not supported on", runtime.GOOS) 24 return 25 } 26 27 c, err := icmp.ListenPacket("udp6", "fe80::1%en0") 28 if err != nil { 29 log.Fatal(err) 30 } 31 defer c.Close() 32 33 wm := icmp.Message{ 34 Type: ipv6.ICMPTypeEchoRequest, Code: 0, 35 Body: &icmp.Echo{ 36 ID: os.Getpid() & 0xffff, Seq: 1, 37 Data: []byte("HELLO-R-U-THERE"), 38 }, 39 } 40 wb, err := wm.Marshal(nil) 41 if err != nil { 42 log.Fatal(err) 43 } 44 if _, err := c.WriteTo(wb, &net.UDPAddr{IP: net.ParseIP("ff02::1"), Zone: "en0"}); err != nil { 45 log.Fatal(err) 46 } 47 48 rb := make([]byte, 1500) 49 n, peer, err := c.ReadFrom(rb) 50 if err != nil { 51 log.Fatal(err) 52 } 53 rm, err := icmp.ParseMessage(58, rb[:n]) 54 if err != nil { 55 log.Fatal(err) 56 } 57 switch rm.Type { 58 case ipv6.ICMPTypeEchoReply: 59 log.Printf("got reflection from %v", peer) 60 default: 61 log.Printf("got %+v; want echo reply", rm) 62 } 63 }