github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/transport/internet/tcp_hub.go (about) 1 package internet 2 3 import ( 4 "context" 5 6 "v2ray.com/core/common/net" 7 ) 8 9 var ( 10 transportListenerCache = make(map[string]ListenFunc) 11 ) 12 13 func RegisterTransportListener(protocol string, listener ListenFunc) error { 14 if _, found := transportListenerCache[protocol]; found { 15 return newError(protocol, " listener already registered.").AtError() 16 } 17 transportListenerCache[protocol] = listener 18 return nil 19 } 20 21 type ConnHandler func(Connection) 22 23 type ListenFunc func(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) 24 25 type Listener interface { 26 Close() error 27 Addr() net.Addr 28 } 29 30 func ListenTCP(ctx context.Context, address net.Address, port net.Port, settings *MemoryStreamConfig, handler ConnHandler) (Listener, error) { 31 if settings == nil { 32 s, err := ToMemoryStreamConfig(nil) 33 if err != nil { 34 return nil, newError("failed to create default stream settings").Base(err) 35 } 36 settings = s 37 } 38 39 if address.Family().IsDomain() && address.Domain() == "localhost" { 40 address = net.LocalHostIP 41 } 42 43 if address.Family().IsDomain() { 44 return nil, newError("domain address is not allowed for listening: ", address.Domain()) 45 } 46 47 protocol := settings.ProtocolName 48 listenFunc := transportListenerCache[protocol] 49 if listenFunc == nil { 50 return nil, newError(protocol, " listener not registered.").AtError() 51 } 52 listener, err := listenFunc(ctx, address, port, settings, handler) 53 if err != nil { 54 return nil, newError("failed to listen on address: ", address, ":", port).Base(err) 55 } 56 return listener, nil 57 } 58 59 // ListenSystem listens on a local address for incoming TCP connections. 60 // 61 // v2ray:api:beta 62 func ListenSystem(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.Listener, error) { 63 return effectiveListener.Listen(ctx, addr, sockopt) 64 } 65 66 // ListenSystemPacket listens on a local address for incoming UDP connections. 67 // 68 // v2ray:api:beta 69 func ListenSystemPacket(ctx context.Context, addr net.Addr, sockopt *SocketConfig) (net.PacketConn, error) { 70 return effectiveListener.ListenPacket(ctx, addr, sockopt) 71 }