Debian Codegraph @

examples/vnet-udpproxy/main.go

raw symbols SCIP
1 // Package main implements an example for the virtual Net
2 // UDP proxy.
3 package main
4
5 import (
6 "flag"
7 "net"
8 "time"
9
10 "github.com/pion/logging"
11 "github.com/pion/transport/v2/vnet"
12 )
13
14 func main() {
15 address := flag.String("address", "", "Destination address that three separate vnet clients will send too")
16 flag.Parse()
17
18 // Create vnet WAN with one endpoint
19 // See the following docs for more information
20 // https://github.com/pion/transport/tree/master/vnet#example-wan-with-one-endpoint-vnet
21 router, err := vnet.NewRouter(&vnet.RouterConfig{
22 CIDR: "0.0.0.0/0",
23 LoggerFactory: logging.NewDefaultLoggerFactory(),
24 })
25 if err != nil {
26 panic(err)
27 }
28
29 // Create a network and add to router, for example, for client.
30 clientNetwork, err := vnet.NewNet(&vnet.NetConfig{
31 StaticIP: "10.0.0.11",
32 })
33 if err != nil {
34 panic(err)
35 }
36
37 if err = router.AddNet(clientNetwork); err != nil {
38 panic(err)
39 }
40
41 if err = router.Start(); err != nil {
42 panic(err)
43 }
44 defer router.Stop() // nolint:errcheck
45
46 // Create a proxy, bind to the router.
47 proxy, err := vnet.NewProxy(router)
48 if err != nil {
49 panic(err)
50 }
51 defer proxy.Close() // nolint:errcheck
52
53 serverAddr, err := net.ResolveUDPAddr("udp4", *address)
54 if err != nil {
55 panic(err)
56 }
57
58 // Start to proxy some addresses, clientNetwork is a hit for proxy,
59 // that the client in vnet is from this network.
60 if err = proxy.Proxy(clientNetwork, serverAddr); err != nil {
61 panic(err)
62 }
63
64 // Now, all packets from client, will be proxy to real server, vice versa.
65 client0, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5787")
66 if err != nil {
67 panic(err)
68 }
69 _, _ = client0.WriteTo([]byte("Hello"), serverAddr)
70
71 client1, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5788")
72 if err != nil {
73 panic(err)
74 }
75 _, _ = client1.WriteTo([]byte("Hello"), serverAddr)
76
77 client2, err := clientNetwork.ListenPacket("udp4", "10.0.0.11:5789")
78 if err != nil {
79 panic(err)
80 }
81 _, _ = client2.WriteTo([]byte("Hello"), serverAddr)
82
83 // Packets are delivered by a goroutine so WriteTo
84 // return doesn't mean success. This may improve in
85 // the future.
86 time.Sleep(time.Second * 3)
87 }