easyp2p

package
v2.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LANMulticastIP   = "239.255.255.250"
	LANMulticastPort = 19730
	LANBeaconMagic   = "GONC-LAN-V1"
	LANNonceSize     = 16
)
View Source
const (
	// CapLANProbe 能力标识,用于 exchangeAddressPayload.Caps 版本协商
	CapLANProbe = "lan-probe"
)
View Source
const (
	// CapMultiExitUDPPunch 能力标识,支持并行UDP打洞
	CapMultiExitUDPPunch = "multi-exit-udp-punch"
)
View Source
const DefaultPunchingShortTTL = 5

Variables

View Source
var (
	TopicExchange              = "nat-exchange/"
	MQTTBrokerServers []string = []string{
		"tcp://broker.hivemq.com:1883",
		"tcp://broker.emqx.io:1883",
		"tcp://test.mosquitto.org:1883",
		"tcp://guest:guest@mqtt.gonc.cc:1883",
	}

	PunchingShortTTL        int = DefaultPunchingShortTTL
	PunchingRandomPortCount int = 600

	TopicDesc_WAIT            = "WT"
	TopicDesc_HELLO           = "HL"
	TopicDesc_ExchangeAddress = "EA"
	TopicDesc_RoundSync       = "RS"
)
View Source
var (
	EXMODE_mutual   int = 0
	EXMODE_waitOnly int = 1
	EXMODE_reply    int = 2
)
View Source
var (
	STUNServers []string = []string{
		"tcp://turn.cloudflare.com:80",
		"udp://turn.cloudflare.com:53?3478",
		"udp://stun.l.google.com:19302",
		"udp://stun.miwifi.com:3478",
		"global.turn.twilio.com:3478",
		"stun.nextcloud.com:443",
	}
)

Functions

func Auto_P2P_TCP_NAT_Traversal

func Auto_P2P_TCP_NAT_Traversal(ctx context.Context, network, sessionUid string, p2pInfo *P2PAddressInfo, sessCtx *P2PSessionContext, round int, logWriter io.Writer) (net.Conn, bool, error)

func Auto_P2P_UDP_NAT_Traversal

func Auto_P2P_UDP_NAT_Traversal(ctx context.Context, network, sessionUid string, p2pInfo *P2PAddressInfo, sessCtx *P2PSessionContext, round int, relayConn *RelayPacketConn, logWriter io.Writer) (net.Conn, bool, bool, error)

func CalculateMD5

func CalculateMD5(input string) string

func CompareP2PAddresses

func CompareP2PAddresses(info *P2PAddressInfo) (sameNATIP bool, similarLAN bool)

func CreateUDPConnFromAddr

func CreateUDPConnFromAddr(laddr, raddr net.Addr, forcelyBind bool) (net.Conn, error)

func DetectNATAddressInfo added in v2.3.8

func DetectNATAddressInfo(networks []string, bind string, relayConn *RelayPacketConn, logWriter io.Writer) ([]PunchingAddressInfo, []*STUNResult, error)

func Do_autoP2P

func Do_autoP2P(network string, sessionUid string, stunServers, brokerServers []string, timeout time.Duration, needSharedKey bool, logWriter io.Writer) (*P2PAddressInfo, *P2PSessionContext, error)

func Do_autoP2PEx

func Do_autoP2PEx(networks []string, sessionUid string, timeout time.Duration, needSharedKey bool, relayConn *RelayPacketConn, logWriter io.Writer) ([]*P2PAddressInfo, *P2PSessionContext, error)

func Do_autoP2PEx2 added in v2.3.6

func Do_autoP2PEx2(ctx context.Context, networks []string, bind, sessionUid string, timeout time.Duration, needSharedKey bool, relayConn *RelayPacketConn, logWriter io.Writer) ([]*P2PAddressInfo, *P2PSessionContext, error)

func GetFreePort

func GetFreePort() (int, error)

GetFreePort 尝试找到一个可同时绑定 TCP 和 UDP 的端口

func GetPublicIP

func GetPublicIP(network, bind string, timeout time.Duration) (index int, localAddr, natAddr string, err error)

GetPublicIP 获取公网IP,返回第一个成功响应的STUN服务器的结果

func IsIPv6

func IsIPv6(addr string) bool

func IsPeerSameLAN

func IsPeerSameLAN(conn net.Conn) bool

func IsSameLAN

func IsSameLAN(ip1, ip2 string) bool

func IsUnRetryable

func IsUnRetryable(err error) bool

func LANTransportFromConfig added in v2.4.11

func LANTransportFromConfig(udpProtocol bool) string

func MQTTHello added in v2.2.0

func MQTTHello(ctx context.Context, sessionUid, localIP string, helloPayload HelloPayload, timeout time.Duration, logWriter io.Writer) (string, error)

func MQTT_Exchange added in v2.2.0

func MQTT_Exchange(ctx context.Context, exmode int, sendData, topicCID, topicSalt, sessionUid, localIP string, timeout time.Duration, messageHandler func(string) (bool, error)) (recvData string, recvIndex int, err error)

func MQTT_GenerateClientID added in v2.2.2

func MQTT_GenerateClientID(topicDesc, sessionUid string, seed int64) string

no longer than 23 characters

func MQTT_SecureExchange added in v2.2.0

func MQTT_SecureExchange[T any](ctx context.Context, exmode int, sendData any, topicCID, topicSalt, sessionUid, localIP string, timeout time.Duration, messageFilter func(T) (bool, error)) (recvData T, recvIndex int, err error)

func MqttWait

func MqttWait(ctx context.Context, sessionUid, localIP string, timeout time.Duration, logWriter io.Writer) (string, error)

func Mqtt_P2P_Round_Sync

func Mqtt_P2P_Round_Sync(ctx context.Context, sessionUid string, sessCtx *P2PSessionContext, isClient bool, round int, timeout time.Duration, logWriter io.Writer) error

func NetworksForStun added in v2.5.0

func NetworksForStun(network string) ([]string, error)

func ParseMQTTHelloPayload added in v2.4.5

func ParseMQTTHelloPayload(topicSalt string) (control, app, prefix string)

func ParseMQTTServerV3 added in v2.4.3

func ParseMQTTServerV3(input string) (string, url.Values, error)

func SelectRole

func SelectRole(p2pInfo *P2PAddressInfo, sessCtx *P2PSessionContext) bool

func WrapUnRetryable

func WrapUnRetryable(err error) error

Types

type AnalyzedStunResult

type AnalyzedStunResult struct {
	NATType string `json:"nattype"` // "easy", "hard", "symm"
	Network string `json:"network"`
	LAN     string `json:"lan"`
	NAT     string `json:"nat"`
}

type HelloPayload added in v2.4.5

type HelloPayload struct {
	Control []string
	App     string
	Param   string
}

func HelloPayloadFromString added in v2.4.5

func HelloPayloadFromString(topicSalt string) HelloPayload

func (HelloPayload) AppString added in v2.4.5

func (h HelloPayload) AppString() string

func (HelloPayload) CtrlString added in v2.4.7

func (h HelloPayload) CtrlString() string

func (HelloPayload) GetControlValue added in v2.4.5

func (h HelloPayload) GetControlValue(key string) (string, bool)

func (*HelloPayload) SetControlValue added in v2.4.5

func (h *HelloPayload) SetControlValue(key, val string)

func (HelloPayload) String added in v2.4.5

func (h HelloPayload) String() string

type LANDiscoverResult added in v2.4.11

type LANDiscoverResult struct {
	LocalIP     string
	LocalPort   int
	RemoteIP    string
	RemotePort  int
	Transport   string
	IsInitiator bool
}

func LANDiscover added in v2.4.11

func LANDiscover(ctx context.Context, sessionKey, transportPref string, timeout time.Duration, logWriter io.Writer) (*LANDiscoverResult, error)

type NatIPLocalKey

type NatIPLocalKey struct {
	Network string
	Local   string
	NATIP   string // Only NAT IP part
}

NatIPLocalKey serves as a key to group results by NAT IP and local address, to check port consistency for 'hard' vs 'symm' behavior within a specific NAT IP.

type P2PAddressInfo

type P2PAddressInfo struct {
	Network                  string
	LocalLAN                 string
	LocalNAT                 string
	LocalNATType             string
	RemoteLAN                string
	RemoteNAT                string
	RemoteNATType            string
	LANProbeOnly             bool
	RemoteUDP4NATAlternative []string // 对端的其他UDP4 NAT地址(多出口IP并行打洞用)
}

func SortP2PAddressInfos

func SortP2PAddressInfos(addrs []*P2PAddressInfo) []*P2PAddressInfo

SortP2PAddressInfos takes a slice of *P2PAddressInfo pointers, sorts it based on the specified priority, and returns the sorted slice. The original slice is not modified.

type P2PConnInfo

type P2PConnInfo struct {
	Conns        []net.Conn
	SharedKey    [32]byte
	IsClient     bool
	RelayUsed    bool
	RelayMode    bool
	NetworksUsed []string
	PeerAddress  string
}

func Easy_P2P

func Easy_P2P(network, sessionUid string, relayConn *RelayPacketConn, logWriter io.Writer) (*P2PConnInfo, error)

func Easy_P2P_LAN added in v2.4.11

func Easy_P2P_LAN(ctx context.Context, sessionKey, transportPref string, timeout time.Duration, logWriter io.Writer) (*P2PConnInfo, error)

func Easy_P2P_MP

func Easy_P2P_MP(ctx context.Context, network, bind, sessionUid string, multipathEnabled bool, relayConn *RelayPacketConn, logWriter io.Writer) (*P2PConnInfo, error)

type P2PSessionContext added in v2.5.0

type P2PSessionContext struct {
	SharedKey             [32]byte
	LocalBindIP           string
	LocalPublicIPv4Count  int // 本端公网IPv4出口数量,用于调整打洞策略
	LocalPublicIPv6Count  int
	RemotePublicIPv4Count int
	RemotePublicIPv6Count int
	RelayAvailable        bool
	LocalCaps             []string
	RemoteCaps            []string
}

P2PSessionContext 描述一次打洞会话的全局上下文(所有候选共享)

type PunchingAddressInfo added in v2.0.1

type PunchingAddressInfo struct {
	Network string `json:"network"` // 网络名称, 例如 "tcp", "udp"
	NatType string `json:"nattype"` // NAT 类型
	Lan     string `json:"lan"`     // 局域网地址
	Nat     string `json:"nat"`     // 公网地址
}

type RelayPacketConn added in v2.2.2

type RelayPacketConn struct {
	net.PacketConn
	FallbackMode bool
}

type STUNResult

type STUNResult struct {
	Index   int // Original index of the STUN server in the input slice
	Network string
	Local   string // Local IP address and port used for the STUN request
	Nat     string // NAT IP address and port returned by the STUN server
	Remote  string // Stun Server address used
	Err     error  // Error, if any, encountered during the STUN request
}

STUNResult struct holds the outcome of a single STUN request. It's used both internally and as the return type for the function.

func GetNetworksPublicIPs

func GetNetworksPublicIPs(networkList []string, bind string, timeout time.Duration, shPktCon net.PacketConn) ([]*STUNResult, error)

func GetPublicIPs

func GetPublicIPs(network, bind string, timeout time.Duration, natIPUniq bool, shPktCon net.PacketConn) ([]*STUNResult, error)

GetPublicIPs attempts to discover public IP addresses using STUN servers. It collects as many unique NAT IP addresses (by IP address only, ignoring port) as possible within the specified timeout, and returns all results (unique successful ones and errors).

type UnRetryableError

type UnRetryableError struct {
	Err error
}

func (UnRetryableError) Error

func (e UnRetryableError) Error() string

func (UnRetryableError) Unwrap

func (e UnRetryableError) Unwrap() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL