MCPcopy Create free account
hub / github.com/encodeous/nylon / main

Function main

polyamide/tun/netstack/examples/ping_client.go:25–75  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

23)
24
25func 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
35public_key=25123c5dcd3328ff645e4f2a3fce0d754400d3887a0cb7c56f0267e20fbf3c5b
36endpoint=163.172.161.0:12912
37allowed_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}

Callers

nothing calls this directly

Calls 10

IpcSetMethod · 0.95
UpMethod · 0.95
CreateNetTUNFunction · 0.92
NewDeviceFunction · 0.92
NewDefaultBindFunction · 0.92
NewLoggerFunction · 0.92
DialMethod · 0.80
WriteMethod · 0.65
ReadMethod · 0.65
SetReadDeadlineMethod · 0.45

Tested by

no test coverage detected