dialer.go 778 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package dialer
  2. import (
  3. "errors"
  4. "math/rand"
  5. "net"
  6. v2net "github.com/v2ray/v2ray-core/common/net"
  7. )
  8. var (
  9. ErrInvalidHost = errors.New("Invalid Host.")
  10. )
  11. func Dial(dest v2net.Destination) (net.Conn, error) {
  12. var ip net.IP
  13. if dest.Address().IsIPv4() || dest.Address().IsIPv6() {
  14. ip = dest.Address().IP()
  15. } else {
  16. ips, err := net.LookupIP(dest.Address().Domain())
  17. if err != nil {
  18. return nil, err
  19. }
  20. if len(ips) == 0 {
  21. return nil, ErrInvalidHost
  22. }
  23. if len(ips) == 1 {
  24. ip = ips[0]
  25. } else {
  26. ip = ips[rand.Intn(len(ips))]
  27. }
  28. }
  29. if dest.IsTCP() {
  30. return net.DialTCP("tcp", nil, &net.TCPAddr{
  31. IP: ip,
  32. Port: int(dest.Port()),
  33. })
  34. } else {
  35. return net.DialUDP("udp", nil, &net.UDPAddr{
  36. IP: ip,
  37. Port: int(dest.Port()),
  38. })
  39. }
  40. }