github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/common/net/destination.go (about) 1 package net 2 3 import ( 4 "net" 5 "strings" 6 ) 7 8 // Destination represents a network destination including address and protocol (tcp / udp). 9 type Destination struct { 10 Address Address 11 Port Port 12 Network Network 13 } 14 15 // DestinationFromAddr generates a Destination from a net address. 16 func DestinationFromAddr(addr net.Addr) Destination { 17 switch addr := addr.(type) { 18 case *net.TCPAddr: 19 return TCPDestination(IPAddress(addr.IP), Port(addr.Port)) 20 case *net.UDPAddr: 21 return UDPDestination(IPAddress(addr.IP), Port(addr.Port)) 22 case *net.UnixAddr: 23 // TODO: deal with Unix domain socket 24 return TCPDestination(LocalHostIP, Port(9)) 25 default: 26 panic("Net: Unknown address type.") 27 } 28 } 29 30 // ParseDestination converts a destination from its string presentation. 31 func ParseDestination(dest string) (Destination, error) { 32 d := Destination{ 33 Address: AnyIP, 34 Port: Port(0), 35 } 36 if strings.HasPrefix(dest, "tcp:") { 37 d.Network = Network_TCP 38 dest = dest[4:] 39 } else if strings.HasPrefix(dest, "udp:") { 40 d.Network = Network_UDP 41 dest = dest[4:] 42 } 43 44 hstr, pstr, err := SplitHostPort(dest) 45 if err != nil { 46 return d, err 47 } 48 if len(hstr) > 0 { 49 d.Address = ParseAddress(hstr) 50 } 51 if len(pstr) > 0 { 52 port, err := PortFromString(pstr) 53 if err != nil { 54 return d, err 55 } 56 d.Port = port 57 } 58 return d, nil 59 } 60 61 // TCPDestination creates a TCP destination with given address 62 func TCPDestination(address Address, port Port) Destination { 63 return Destination{ 64 Network: Network_TCP, 65 Address: address, 66 Port: port, 67 } 68 } 69 70 // UDPDestination creates a UDP destination with given address 71 func UDPDestination(address Address, port Port) Destination { 72 return Destination{ 73 Network: Network_UDP, 74 Address: address, 75 Port: port, 76 } 77 } 78 79 // NetAddr returns the network address in this Destination in string form. 80 func (d Destination) NetAddr() string { 81 return d.Address.String() + ":" + d.Port.String() 82 } 83 84 // String returns the strings form of this Destination. 85 func (d Destination) String() string { 86 prefix := "unknown:" 87 switch d.Network { 88 case Network_TCP: 89 prefix = "tcp:" 90 case Network_UDP: 91 prefix = "udp:" 92 } 93 return prefix + d.NetAddr() 94 } 95 96 // IsValid returns true if this Destination is valid. 97 func (d Destination) IsValid() bool { 98 return d.Network != Network_Unknown 99 } 100 101 // AsDestination converts current Endpoint into Destination. 102 func (p *Endpoint) AsDestination() Destination { 103 return Destination{ 104 Network: p.Network, 105 Address: p.Address.AsAddress(), 106 Port: Port(p.Port), 107 } 108 }