github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/tunnel/freedom/conn.go (about) 1 package freedom 2 3 import ( 4 "net" 5 6 "github.com/laof/lite-speed-test/common" 7 "github.com/laof/lite-speed-test/tunnel" 8 ) 9 10 type Conn struct { 11 net.Conn 12 } 13 14 func (c *Conn) Metadata() *tunnel.Metadata { 15 return nil 16 } 17 18 type PacketConn struct { 19 *net.UDPConn 20 } 21 22 func (c *PacketConn) WriteWithMetadata(p []byte, m *tunnel.Metadata) (int, error) { 23 return c.WriteTo(p, m.Address) 24 } 25 26 func (c *PacketConn) ReadWithMetadata(p []byte) (int, *tunnel.Metadata, error) { 27 n, addr, err := c.ReadFrom(p) 28 if err != nil { 29 return 0, nil, err 30 } 31 address, err := tunnel.NewAddressFromAddr("udp", addr.String()) 32 common.Must(err) 33 metadata := &tunnel.Metadata{ 34 Address: address, 35 } 36 return n, metadata, nil 37 } 38 39 func (c *PacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { 40 if udpAddr, ok := addr.(*net.UDPAddr); ok { 41 return c.WriteToUDP(p, udpAddr) 42 } 43 ip, err := addr.(*tunnel.Address).ResolveIP() 44 if err != nil { 45 return 0, err 46 } 47 udpAddr := &net.UDPAddr{ 48 IP: ip, 49 Port: addr.(*tunnel.Address).Port, 50 } 51 return c.WriteToUDP(p, udpAddr) 52 }