dialer.go 756 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package dialer
  2. import (
  3. "errors"
  4. "net"
  5. "github.com/v2ray/v2ray-core/common/dice"
  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. ip = ips[dice.Roll(len(ips))]
  24. }
  25. if dest.IsTCP() {
  26. return net.DialTCP("tcp", nil, &net.TCPAddr{
  27. IP: ip,
  28. Port: int(dest.Port()),
  29. })
  30. } else {
  31. return net.DialUDP("udp", nil, &net.UDPAddr{
  32. IP: ip,
  33. Port: int(dest.Port()),
  34. })
  35. }
  36. }