gitee.com/aurawing/surguard-go@v0.3.1-0.20240409071558-96509a61ecf3/tun/netstack/examples/ping_client.go (about) 1 //go:build ignore 2 3 /* SPDX-License-Identifier: MIT 4 * 5 * Copyright (C) 2017-2023 WireGuard LLC. All Rights Reserved. 6 */ 7 8 package main 9 10 import ( 11 "bytes" 12 "log" 13 "math/rand" 14 "net/netip" 15 "time" 16 17 "golang.org/x/net/icmp" 18 "golang.org/x/net/ipv4" 19 20 "gitee.com/aurawing/surguard-go/conn" 21 "gitee.com/aurawing/surguard-go/device" 22 "gitee.com/aurawing/surguard-go/tun/netstack" 23 ) 24 25 func main() { 26 tun, tnet, err := netstack.CreateNetTUN( 27 []netip.Addr{netip.MustParseAddr("192.168.4.29")}, 28 []netip.Addr{netip.MustParseAddr("8.8.8.8")}, 29 1420) 30 if err != nil { 31 log.Panic(err) 32 } 33 dev := device.NewDevice(tun, conn.NewDefaultBind(), device.NewLogger(device.LogLevelVerbose, "")) 34 dev.IpcSet(`private_key=a8dac1d8a70a751f0f699fb14ba1cff7b79cf4fbd8f09f44c6e6a90d0369604f 35 public_key=25123c5dcd3328ff645e4f2a3fce0d754400d3887a0cb7c56f0267e20fbf3c5b 36 endpoint=163.172.161.0:12912 37 allowed_ip=0.0.0.0/0 38 `) 39 err = dev.Up() 40 if err != nil { 41 log.Panic(err) 42 } 43 44 socket, err := tnet.Dial("ping4", "zx2c4.com") 45 if err != nil { 46 log.Panic(err) 47 } 48 requestPing := icmp.Echo{ 49 Seq: rand.Intn(1 << 16), 50 Data: []byte("gopher burrow"), 51 } 52 icmpBytes, _ := (&icmp.Message{Type: ipv4.ICMPTypeEcho, Code: 0, Body: &requestPing}).Marshal(nil) 53 socket.SetReadDeadline(time.Now().Add(time.Second * 10)) 54 start := time.Now() 55 _, err = socket.Write(icmpBytes) 56 if err != nil { 57 log.Panic(err) 58 } 59 n, err := socket.Read(icmpBytes[:]) 60 if err != nil { 61 log.Panic(err) 62 } 63 replyPacket, err := icmp.ParseMessage(1, icmpBytes[:n]) 64 if err != nil { 65 log.Panic(err) 66 } 67 replyPing, ok := replyPacket.Body.(*icmp.Echo) 68 if !ok { 69 log.Panicf("invalid reply type: %v", replyPacket) 70 } 71 if !bytes.Equal(replyPing.Data, requestPing.Data) || replyPing.Seq != requestPing.Seq { 72 log.Panicf("invalid ping reply: %v", replyPing) 73 } 74 log.Printf("Ping latency: %v", time.Since(start)) 75 }