1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-19 02:16:11 -04:00
v2fly/transport/hub/dialer.go

64 lines
1.1 KiB
Go
Raw Normal View History

2016-05-30 18:21:41 -04:00
package hub
import (
"errors"
"net"
"time"
v2net "github.com/v2ray/v2ray-core/common/net"
2016-06-01 19:49:25 -04:00
"github.com/v2ray/v2ray-core/transport"
2016-05-30 18:21:41 -04:00
)
var (
ErrorInvalidHost = errors.New("Invalid Host.")
globalCache = NewConnectionCache()
)
func Dial(dest v2net.Destination) (*Connection, error) {
destStr := dest.String()
2016-06-01 19:49:25 -04:00
var conn net.Conn
2016-06-02 14:52:52 -04:00
if transport.IsConnectionReusable() {
2016-06-01 19:49:25 -04:00
conn = globalCache.Get(destStr)
}
2016-05-30 18:21:41 -04:00
if conn == nil {
var err error
conn, err = DialWithoutCache(dest)
if err != nil {
return nil, err
}
}
return &Connection{
dest: destStr,
conn: conn,
listener: globalCache,
}, nil
}
func DialWithoutCache(dest v2net.Destination) (net.Conn, error) {
if dest.Address().IsDomain() {
dialer := &net.Dialer{
Timeout: time.Second * 60,
DualStack: true,
}
network := "tcp"
if dest.IsUDP() {
network = "udp"
}
return dialer.Dial(network, dest.NetAddr())
}
ip := dest.Address().IP()
if dest.IsTCP() {
return net.DialTCP("tcp", nil, &net.TCPAddr{
IP: ip,
Port: int(dest.Port()),
})
}
return net.DialUDP("udp", nil, &net.UDPAddr{
IP: ip,
Port: int(dest.Port()),
})
}