StunClient 1.0.6

StunClient 1.0.6

madmag77 维护。



  • 作者:
  • madmag77

Swift

StunClient

使用 UDP 连接到 Stun 服务器并请求您的外部 IP 和端口的简单 Stun 客户端。可用于 iOS 和 macOS。

要求

  • iOS 10.0+ / macOS 10.12+
  • Xcode 11+
  • Swift 5.2+

安装

Swift 包管理器

Swift 包管理器 是一个用于自动化 Swift 代码分布的工具,集成到 swift 编译器中。

只需将 Stun Client 添加到您的 Package.swiftdependencies 中。

dependencies: [
    .package(url: "https://github.com/madmag77/STUNClient.git", .upToNextMajor(from: "1.0.3"))
]

或者使用 Xcode 菜单:文件->Swift 包->添加包依赖,在搜索行中 just insert https://github.com/madmag77/STUNClient.git

CocoaPods

CocoaPods 是 Cocoa 项目的依赖管理器。在 Podfile 中添加 StunClient。

pod 'StunClient'

这里您可以找到使用 StunClient 作为 CocoaPod 的 iOS 示例项目:https://github.com/madmag77/STUNClient/tree/master/iOSExampleWithPods

手动

在终端

git clone https://github.com/madmag77/STUNClient
cd STUNClient 
swift run

您应该看到以下输出

LOG: Start Who Am I procedure with Stun server 64.233.163.127:19302 from local port 14135
LOG: XOR_MAPPED_ADDRESS 
 Family: 1 
 Port: 54668  
 Address: xxx.xxx.xxx.xxx
COMPLETED, my address: xxx.xxx.xxx.xxx my port: 54668

然后您可以尝试 iOS 示例

cd iOSExample 
open STUNClient.xcodeproj

选择模拟器并运行项目。

使用方法

这是如何使用 Stun 客户端(这里使用的是 Google Stun IP 地址和端口)的方法

client = StunClient(stunIpAddress: "64.233.163.127", stunPort: 19302, localPort: UInt16(14135))
let successCallback: (String, Int) -> () = { [weak self] (myAddress: String, myPort: Int) in
        guard let self = self else { return }
        
        print("COMPLETED, my address: \(myAddress) my port: \(myPort)")
}
let errorCallback: (StunError) -> () = { [weak self] error in
            guard let self = self else { return }
            
            print("ERROR: \(error.localizedDescription)")
    }
let verboseCallback: (String) -> () = { [weak self] logText in
            guard let _ = self else { return }
            
            print("LOG: \(logText)")
    }

client
    .whoAmI()
    .ifWhoAmISuccessful(successCallback)
    .ifError(errorCallback)
    .verbose(verboseCallback)
    .start()