### Example invocations for NatTypeTester.Console Source: https://github.com/hmbsbige/nattypetester Three example command-line invocations: RFC 3489 test over UDP, RFC 5780 full discovery over UDP, and RFC 5780 mapping test over TLS through SOCKS5 with certificate validation skipped. The third command uses line continuation with a backslash. ```bash # Classic RFC 3489 test over UDP NatTypeTester.Console rfc3489 -s stun.syncthing.net ``` ```bash # RFC 5780 full discovery over UDP NatTypeTester.Console rfc5780 -s stun.example.com --test-type combining --transport udp ``` ```bash # RFC 5780 mapping test over TLS through SOCKS5, skipping cert validation NatTypeTester.Console rfc5780 -s stun.example.com -t tls --test-type mapping \ --proxy 127.0.0.1:1080 --proxy-user u --proxy-password p --skip-cert ``` -------------------------------- ### StunClient5389UDP usage example Source: https://github.com/hmbsbige/nattypetester Example of creating a StunClient5389UDP client, connecting the proxy, running the full RFC 5780 discovery via QueryAsync, and printing the binding test result, mapping behavior, and filtering behavior. The proxy is closed in a finally block to ensure cleanup. ```csharp using STUN.Client; using System.Net; await using StunClient5389UDP client = new( IPEndPoint.Parse("203.0.113.10:3478"), new IPEndPoint(IPAddress.Any, 0)); await client.ConnectProxyAsync(); try { await client.QueryAsync(); Console.WriteLine(client.State.BindingTestResult); Console.WriteLine(client.State.MappingBehavior); Console.WriteLine(client.State.FilteringBehavior); } finally { await client.CloseProxyAsync(); } ``` -------------------------------- ### Host an embedded views setup — Program.cs Source: https://github.com/hmbsbige/nattypetester Configures an Avalonia app with platform detection, registers all modules and exception handling via UseNatTypeTesterApp(), and starts the classic desktop lifetime. Requires the NatTypeTester.Views and NatTypeTester.Views.Infrastructure namespaces. ```csharp // Program.cs (any Avalonia host) using NatTypeTester.Views; using NatTypeTester.Views.Infrastructure; AppBuilder.Configure() .UsePlatformDetect() .UseNatTypeTesterApp() // registers all modules + exception handling .LogToTrace() .StartWithClassicDesktopLifetime(args); ``` -------------------------------- ### Full application bootstrap example Source: https://github.com/hmbsbige/nattypetester Shows how to set up the application services and run a STUN test. It builds a ServiceProvider with validation enabled, resolves IRfc5780AppService, and calls TestAsync with a StunTestInput. Catches ArgumentException for invalid input and writes to console error. ```csharp using Microsoft.Extensions.DependencyInjection; using NatTypeTester.Application; using NatTypeTester.Application.Contracts; using STUN.Enums; await using ServiceProvider services = new ServiceCollection() .AddNatTypeTesterApplication() .BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }); try { StunResult5389 result = await services.GetRequiredService().TestAsync( new StunTestInput { StunServer = "stun.example.com" }, TransportType.Udp); Console.WriteLine($"Binding: {result.BindingTestResult}"); } catch (ArgumentException ex) { Console.Error.WriteLine($"Invalid input: {ex.Message}"); } ``` -------------------------------- ### Manual driving example for Stun3489NatTypeDiscovery Source: https://github.com/hmbsbige/nattypetester Shows how to manually drive the discovery machine: create the query, loop sending and receiving responses, and call GotResponse until it returns null. Then print the resulting NatType. ```csharp using STUN.Client; using System.Net; Stun3489NatTypeDiscovery discovery = new(IPEndPoint.Parse("203.0.113.10:3478")); StunDiscoveryAction? action = discovery.CreateQuery(); while (action is not null) { StunResponse? response = await SendAndReceiveAsync(action); // your transport action = discovery.GotResponse(response); } Console.WriteLine(discovery.Result.NatType); ``` -------------------------------- ### Mapping-behavior-only driving example Source: https://github.com/hmbsbige/nattypetester Shows how to drive the discovery machine for mapping-behavior-only scope. Creates a Stun5389NatBehaviorDiscovery for a given server, loops sending the action's message and feeding the response back until no further action, then prints the resulting MappingBehavior. ```csharp using STUN.Client; using STUN.Messages; using System.Net; Stun5389NatBehaviorDiscovery discovery = new(IPEndPoint.Parse("203.0.113.10:3478")); StunDiscoveryAction? action = discovery.CreateMappingBehaviorTest(); while (action is not null) { StunResponse? response = await ExchangeAsync(action.Message, action.SendTo); action = discovery.GotResponse(response); } Console.WriteLine(discovery.Result.MappingBehavior); ``` -------------------------------- ### Example: using IAppConfigManager with DI Source: https://github.com/hmbsbige/nattypetester Shows how to configure and retrieve the configuration manager via dependency injection. Sets a custom config file path, builds the service provider, then reads and updates the config asynchronously. ```csharp using Microsoft.Extensions.DependencyInjection; using NatTypeTester.Configuration; using NatTypeTester.Domain.Configuration; ServiceProvider services = new ServiceCollection() .Configure(options => options.FilePath = @"./custom-config.json") .AddNatTypeTesterConfiguration() .BuildServiceProvider(); IAppConfigManager manager = services.GetRequiredService(); AppConfig config = await manager.GetAsync(); Console.WriteLine(string.Join(", ", config.StunServers)); await manager.UpdateAsync(c => { c.Language = "zh-Hans"; c.CurrentStunServer = "stun.example.com"; }); ``` -------------------------------- ### Build, send, and validate a STUN reply Source: https://github.com/hmbsbige/nattypetester Example showing how to create a BindingRequest, serialize it, send via UDP, receive a reply, and validate the transaction. Uses the WriteTo and TryParse methods. ```csharp using STUN.Messages; using System.Buffers; using System.Net; using System.Net.Sockets; StunMessage5389 request = new() { StunMessageType = StunMessageType.BindingRequest }; byte[] buffer = new byte[request.Length]; int written = request.WriteTo(buffer); using Socket socket = new(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.SendTo(buffer, 0, written, SocketFlags.None, IPEndPoint.Parse("203.0.113.10:3478")); byte[] reply = socket.Receive(0x10000); StunMessage5389 response = new(); if (response.TryParse(reply) && response.IsSameTransaction(request)) { Console.WriteLine(string.Join(", ", response.Attributes.Select(a => a.Type))); } ``` -------------------------------- ### Example — services in use (identical shape to the Console CLI) Source: https://github.com/hmbsbige/nattypetester Shows how to resolve IRfc5780AppService and call TestAsync. Protocol-level failures are surfaced as result enum values (Fail, UnsupportedServer, ...), not exceptions; ArgumentException is reserved for malformed inputs (bad server string, bad proxy address, bad local endpoint) and surfaces from TestAsync/BindingTestAsync/... ```csharp using Microsoft.Extensions.DependencyInjection; using NatTypeTester.Application.Contracts; using STUN.Enums; await using ServiceProvider services = new ServiceCollection() .AddNatTypeTesterApplication() .BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true }); IRfc5780AppService app = services.GetRequiredService(); StunResult5389 result = await app.TestAsync( new StunTestInput { StunServer = "stun.example.com", Proxy = new ProxyOptions { Type = ProxyType.Socks5, Server = "127.0.0.1:1080" }, LocalEndPoint = null, SkipCertificateValidation = false }, TransportType.Udp); Console.WriteLine($"{result.BindingTestResult} / {result.MappingBehavior} / {result.FilteringBehavior}"); if (result.BindingTestResult is BindingTestResult.UnsupportedServer) { // treat as configuration/network error; no exception is thrown for protocol-level failures } ``` -------------------------------- ### CreateProxy usage example with Socks5 UDP proxy Source: https://github.com/hmbsbige/nattypetester Shows how to create a Socks5 UDP proxy using ProxyFactory.CreateProxy, connect, send and receive data, then close and dispose. Requires a Socks5 server at 127.0.0.1:1080 with the given credentials. The targetHost is used for SNI in TLS/DTLS scenarios. ```csharp using Socks5.Models; using STUN.Enums; using STUN.Proxy; using System.Net; IPEndPoint local = new(IPAddress.Any, 0); IUdpProxy proxy = ProxyFactory.CreateProxy( transport: TransportType.Udp, type: ProxyType.Socks5, local: local, option: new Socks5CreateOption { Address = IPAddress.Parse("127.0.0.1"), Port = 1080, UsernamePassword = new UsernamePassword { UserName = "user", Password = "pass" } }, targetHost: "stun.example.com"); await proxy.ConnectAsync(); try { int sent = await proxy.SendToAsync(payload, SocketFlags.None, IPEndPoint.Parse("203.0.113.10:3478")); SocketReceiveMessageFromResult reply = await proxy.ReceiveMessageFromAsync(buffer, SocketFlags.None, IPEndPoint.Parse("203.0.113.10:3478")); } finally { await proxy.CloseAsync(); await proxy.DisposeAsync(); } ``` -------------------------------- ### Example: using AddNatTypeTesterDomainShared and accessing configuration Source: https://github.com/hmbsbige/nattypetester Builds a ServiceProvider with the extension, retrieves the TimeProvider, and prints configuration constants and a localized label. ```csharp using Microsoft.Extensions.DependencyInjection; using NatTypeTester.Domain.Shared; using NatTypeTester.Domain.Shared.Configuration; using NatTypeTester.Domain.Shared.Localization; ServiceProvider services = new ServiceCollection() .AddNatTypeTesterDomainShared() .BuildServiceProvider(); TimeProvider clock = services.GetRequiredService(); Console.WriteLine(ConfigurationConsts.ConfigFilePath); Console.WriteLine(string.Join(", ", ConfigurationConsts.DefaultStunServers)); Console.WriteLine(NatTypeTesterLanguage.Current.StunServer); // localized label ``` -------------------------------- ### HostnameEndpoint.TryParse example with IPv6 Source: https://github.com/hmbsbige/nattypetester Parses the IPv6 endpoint "[2001:db8::1]:5349" and prints it back. The output is "[2001:db8::1]:5349" because ToString() brackets IPv6 addresses. ```csharp using STUN; HostnameEndpoint.TryParse("[2001:db8::1]:5349", out HostnameEndpoint? endPoint); Console.WriteLine(endPoint?.ToString()); // "[2001:db8::1]:5349" ``` -------------------------------- ### StunServer.TryParse usage example Source: https://github.com/hmbsbige/nattypetester Parses a STUN server string with a custom default port (5349 for TLS). On success, prints the server's ToString output, which omits the port when it equals the default. Requires the STUN namespace. ```csharp using STUN; if (StunServer.TryParse("stun.example.com:5349", out StunServer? server, StunServer.DefaultTlsPort)) { Console.WriteLine(server); // "stun.example.com:5349" } ``` -------------------------------- ### StunClient5389TCP usage example Source: https://github.com/hmbsbige/nattypetester Creates a TCP STUN client with a public server endpoint and an ephemeral local endpoint, runs BindingTestAsync, prints the public endpoint, and disposes the client in a finally block. ```csharp using STUN.Client; using System.Net; StunClient5389TCP client = new( IPEndPoint.Parse("203.0.113.10:3478"), new IPEndPoint(IPAddress.Any, 0)); try { StunResult5389 result = await client.BindingTestAsync(); Console.WriteLine(result.PublicEndPoint); } finally { client.Dispose(); } ``` -------------------------------- ### Combine multiple test results into one StunResult5389 Source: https://github.com/hmbsbige/nattypetester Example showing how to aggregate results from multiple STUN tests into a single StunResult5389 object and check for direct mapping behavior. ```csharp using STUN.Client; StunResult5389 combined = new() { BindingTestResult = udpClient.State.BindingTestResult, MappingBehavior = udpClient.State.MappingBehavior, FilteringBehavior = udpClient.State.FilteringBehavior, PublicEndPoint = udpClient.State.PublicEndPoint, LocalEndPoint = udpClient.State.LocalEndPoint, OtherEndPoint = udpClient.State.OtherEndPoint }; if (combined.MappingBehavior == STUN.Enums.MappingBehavior.Direct) { Console.WriteLine("No NAT detected."); } ``` -------------------------------- ### UseNatTypeTesterApp extension method signature Source: https://github.com/hmbsbige/nattypetester Avalonia AppBuilder extension used by both hosts. Wires the Microsoft DI resolver into ReactiveUI's AppLocator via UseReactiveUIWithMicrosoftDependencyResolver, configures services with AddNatTypeTesterViews, installs NotificationExceptionHandler on resolver built, and sets the ReactiveUI exception handler to NotificationExceptionHandler.ExceptionSignal. ```csharp public static AppBuilder UseNatTypeTesterApp(this AppBuilder builder) ``` -------------------------------- ### ILocalEndPointProvider interface Source: https://github.com/hmbsbige/nattypetester Returns available local endpoints as address:port strings with port 0. The list starts with 0.0.0.0:0 and [::]:0, then all usable unicast addresses of up network interfaces, IPv4 first, sorted by hex address bytes, deduplicated. Usable excludes loopback, IPv4 169.254.x.x, and IPv6 link-local addresses. ```csharp public interface ILocalEndPointProvider { IReadOnlyList GetLocalEndPoints(); } ``` -------------------------------- ### Desktop entry point signature — Program.cs Source: https://github.com/hmbsbige/nattypetester Entry point for the desktop host. Uses STAThread and returns an int. The Main method calls BuildAvaloniaApp().StartWithClassicDesktopLifetime(args) and disposes the locator in a finally block. ```csharp [STAThread] public static int Main(string[] args) ``` -------------------------------- ### DtlsProxy.Client Property Source: https://github.com/hmbsbige/nattypetester Gets the underlying Socket from the inner proxy. ```csharp public Socket Client => innerProxy.Client; ``` -------------------------------- ### ILauncherService interface Source: https://github.com/hmbsbige/nattypetester Launches a URI on the platform shell. The desktop implementation uses Avalonia TopLevel.Launcher. ```csharp public interface ILauncherService { ValueTask LaunchUriAsync(Uri uri); } ``` -------------------------------- ### CreateQuery Method Source: https://github.com/hmbsbige/nattypetester Creates a discovery action that performs binding, filtering, and mapping tests in sequence. ```APIDOC ## CreateQuery ### Description Creates a discovery action for the full NAT behavior discovery (binding + filtering + mapping). ### Method CreateQuery ### Signature ```csharp public StunDiscoveryAction CreateQuery(); ``` ### Returns - **StunDiscoveryAction** - The action to execute for the full discovery. ``` -------------------------------- ### IStunServerListAppService interface Source: https://github.com/hmbsbige/nattypetester Loads a STUN server list from an http(s):// URL via HttpClient or a local file path via File.ReadAllLinesAsync. Each trimmed line is parsed with StunServer.TryParse; valid entries are returned as ToString() forms, and lines that fail to parse are dropped silently. ```csharp public interface IStunServerListAppService { Task> LoadAsync(LoadStunServerListInput input, CancellationToken cancellationToken = default); } ``` -------------------------------- ### ConnectProxyAsync Source: https://github.com/hmbsbige/nattypetester Establishes the connection to the UDP proxy if one is configured. ```csharp public ValueTask ConnectProxyAsync(CancellationToken cancellationToken = default); ``` -------------------------------- ### ConnectProxyAsync Source: https://github.com/hmbsbige/nattypetester Establishes a connection to the configured UDP proxy asynchronously. ```APIDOC ## ConnectProxyAsync ### Description Establishes a connection to the configured UDP proxy asynchronously. ### Method ConnectProxyAsync ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token to cancel the operation. Default: default. ### Response ValueTask - Completes when the connection is established. ### Request Example ```csharp await client.ConnectProxyAsync(); ``` ``` -------------------------------- ### ApplicationSettingsViewModel with Languages and OpenConfigDirectoryCommand Source: https://github.com/hmbsbige/nattypetester Sealed view model managing language options. ApplyConfig populates Languages with an empty system-culture option plus one per NatTypeTesterLanguage.SupportedLanguageTags, selects the configured language, and persists changes. Selected-language changes call NatTypeTesterLanguage.SetCurrent(culture). The generated OpenConfigDirectoryCommand launches the ConfigurationConsts.ConfigDirectory URI via ILauncherService. ```csharp public sealed partial class ApplicationSettingsViewModel : ViewModelBase { public ObservableCollection Languages { get; } = []; [Reactive] public partial LanguageOptionViewModel? SelectedLanguage { get; set; } public static bool CanOpenConfigDirectory { get; } // true on Windows/Linux/macOS } ``` -------------------------------- ### CreateBindingTest Method Source: https://github.com/hmbsbige/nattypetester Creates a discovery action that performs only the binding test and stops after handling the binding test result. ```APIDOC ## CreateBindingTest ### Description Creates a discovery action for the binding test only; stops after `HandleBindingTest`. ### Method CreateBindingTest ### Signature ```csharp public StunDiscoveryAction CreateBindingTest(); ``` ### Returns - **StunDiscoveryAction** - The action to execute for the binding test. ``` -------------------------------- ### AttributeExtensions static class definition Source: https://github.com/hmbsbige/nattypetester Public API of the static AttributeExtensions class in namespace STUN.Utils. Provides factory methods for building STUN attributes and helpers for extracting address attributes from parsed messages. BuildMapping/BuildChangeAddress throw ArgumentOutOfRangeException for families other than IPv4/IPv6; the Get*AddressAttribute helpers throw InvalidOperationException when a matched attribute's value has no Address. ```csharp public static class AttributeExtensions { public static StunAttribute BuildChangeRequest(bool changeIp, bool changePort); public static StunAttribute BuildMapping(IpFamily family, IPAddress ip, ushort port); public static StunAttribute BuildChangeAddress(IpFamily family, IPAddress ip, ushort port); public static IPEndPoint? GetMappedAddressAttribute(this StunMessage5389 response); public static IPEndPoint? GetChangedAddressAttribute(this StunMessage5389 response); public static IPEndPoint? GetXorMappedAddressAttribute(this StunMessage5389 response); public static IPEndPoint? GetOtherAddressAttribute(this StunMessage5389 response); } ``` -------------------------------- ### QueryAsync Source: https://github.com/hmbsbige/nattypetester Performs full RFC 5780 combined discovery (binding, filtering, and mapping) and updates the State property. ```csharp public ValueTask QueryAsync(CancellationToken cancellationToken = default); ``` -------------------------------- ### QueryAsync Source: https://github.com/hmbsbige/nattypetester Runs the mapping behavior test and then sets the filtering behavior to None, as filtering tests apply only to UDP. ```APIDOC ## QueryAsync ### Description Executes the mapping behavior test and then sets `State.FilteringBehavior` to `FilteringBehavior.None`. ### Method ValueTask ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Returns ValueTask ``` -------------------------------- ### CreateMappingBehaviorTest Method Source: https://github.com/hmbsbige/nattypetester Creates a discovery action that performs the binding test followed by mapping behavior tests. ```APIDOC ## CreateMappingBehaviorTest ### Description Creates a discovery action for the binding test, then only mapping tests. ### Method CreateMappingBehaviorTest ### Signature ```csharp public StunDiscoveryAction CreateMappingBehaviorTest(); ``` ### Returns - **StunDiscoveryAction** - The action to execute for mapping behavior discovery. ``` -------------------------------- ### QueryAsync Source: https://github.com/hmbsbige/nattypetester Runs the full RFC 3489 NAT type discovery process. It creates a Stun3489NatTypeDiscovery session, loops through requests and responses until the machine returns null, and updates the State property after each step. ```APIDOC ## QueryAsync ### Description Runs the full RFC 3489 discovery: creates a Stun3489NatTypeDiscovery session, loops RequestAsync → GotResponse until the machine returns null, and copies session.Result into State after each step. ### Method QueryAsync ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token to cancel the operation. Default: default. ### Response ValueTask - Completes when the query is finished. ### Request Example ```csharp await client.QueryAsync(); ``` ``` -------------------------------- ### App class skeleton in App.axaml.cs Source: https://github.com/hmbsbige/nattypetester Defines the Avalonia Application subclass with overrides for Initialize and OnFrameworkInitializationCompleted. On completion, resolves IServiceProvider from AppLocator.Current, sets the main window for desktops, registers the main view for Android and single-view platforms, then posts RunStartupTasks on the UI thread at DispatcherPriority.Loaded. ```csharp public class App : Avalonia.Application { public override void Initialize(); // AvaloniaXamlLoader.Load(this) public override void OnFrameworkInitializationCompleted(); } ``` -------------------------------- ### IUdpProxy.ConnectAsync Source: https://github.com/hmbsbige/nattypetester Establishes the proxy connection for UDP traffic. For direct proxies this is a no-op. ```APIDOC ## ConnectAsync ### Description Establishes the proxy connection for UDP traffic. For direct proxies this is a no-op. ### Method ConnectAsync ### Signature ValueTask ConnectAsync(CancellationToken cancellationToken = default) ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Response - **ValueTask** - Completion of the connection operation. ``` -------------------------------- ### MainWindowViewModel class definition Source: https://github.com/hmbsbige/nattypetester Main window view model exposing RFC3489, RFC5780, and settings view models. RunStartupTasks() is idempotent and loads AppConfig via IAppConfigManager, applies it to SettingsViewModel, then runs the startup update check. ```csharp public class MainWindowViewModel : ViewModelBase { public RFC3489ViewModel RFC3489ViewModel { get; } public RFC5780ViewModel RFC5780ViewModel { get; } public SettingsViewModel SettingsViewModel { get; } public void RunStartupTasks(); } ``` -------------------------------- ### IStunServerListAppService Source: https://github.com/hmbsbige/nattypetester Service interface for loading a STUN server list from a URL or local file path. Parses each line and returns valid entries as strings. ```APIDOC ## IStunServerListAppService ### Description Service interface for loading a STUN server list from a URL or local file path. Parses each line and returns valid entries as strings. ### Members #### LoadAsync - **Signature**: `Task> LoadAsync(LoadStunServerListInput input, CancellationToken cancellationToken = default)` - **Description**: Loads a STUN server list from an `http(s)://` URL (via `HttpClient`) or a local file path (via `File.ReadAllLinesAsync`), parses each trimmed line with `StunServer.TryParse`, and returns the `ToString()` forms of the valid entries (lines that fail to parse are dropped silently). ##### Parameters - **input** (`LoadStunServerListInput`) - Required - Input containing the URL or file path. - **cancellationToken** (`CancellationToken`) - Optional - Cancellation token. ##### Returns - **Task>** - List of valid STUN server strings. ``` -------------------------------- ### GotResponse Method Source: https://github.com/hmbsbige/nattypetester Processes a STUN response and returns the next discovery action, or null if discovery is complete. ```APIDOC ## GotResponse ### Description Handles a STUN response received from the server and advances the state machine. ### Method GotResponse ### Signature ```csharp public StunDiscoveryAction? GotResponse(StunResponse? response); ``` ### Parameters - **response** (StunResponse?) - Required - The STUN response received, or `null` if the request timed out. ### Returns - **StunDiscoveryAction?** - The next action to execute, or `null` if discovery is complete. ``` -------------------------------- ### LoadStunServerListInput DTO Source: https://github.com/hmbsbige/nattypetester Input for loading STUN server lists. Requires Uri (http(s):// URL or local file path). Proxy is used only for HTTP(S) sources and defaults to new() (Plain). ```csharp public sealed class LoadStunServerListInput { public required string Uri { get; init; } public ProxyOptions Proxy { get; init; } = new(); } ``` -------------------------------- ### GetAsync Source: https://github.com/hmbsbige/nattypetester Loads (and caches) the configuration, applying defaults. Returns the current AppConfig instance. ```APIDOC ## GetAsync ### Description Loads (and caches) the config; applies defaults. ### Method GetAsync ### Parameters #### Cancellation Token - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Response #### Success Response - **AppConfig** - The loaded configuration. ### Request Example ```csharp AppConfig config = await manager.GetAsync(); ``` ``` -------------------------------- ### StunClient3489 with SOCKS5 proxy and manual connect/close Source: https://github.com/hmbsbige/nattypetester Runs the same RFC 3489 query through a SOCKS5 UDP proxy. Requires a Socks5UdpProxy configured with a Socks5CreateOption pointing to the proxy address and port. ConnectProxyAsync must be called before QueryAsync, and CloseProxyAsync should be called in a finally block to release the proxy connection. ```csharp using Socks5.Models; using STUN.Client; using STUN.Proxy; using System.Net; IPEndPoint local = new(IPAddress.Any, 0); await using Socks5UdpProxy proxy = new(local, new Socks5CreateOption { Address = IPAddress.Parse("127.0.0.1"), Port = 1080 }); await using StunClient3489 client = new(IPEndPoint.Parse("203.0.113.10:3478"), local, proxy, ownedProxy: true); await client.ConnectProxyAsync(); try { await client.QueryAsync(); } finally { await client.CloseProxyAsync(); } ``` -------------------------------- ### TopLevelHelper class declaration Source: https://github.com/hmbsbige/nattypetester Internal static helper that resolves the Avalonia TopLevel from the current application lifetime: IClassicDesktopStyleApplicationLifetime returns MainWindow, IActivityApplicationLifetime uses TopLevel.GetTopLevel(activityMainView), ISingleViewApplicationLifetime uses TopLevel.GetTopLevel(singleView.MainView), otherwise returns null. ```csharp internal static class TopLevelHelper { public static Control RegisterActivityMainView(Control mainView); public static TopLevel? GetTopLevel(); } ``` -------------------------------- ### ConfigurationConsts configuration constants class Source: https://github.com/hmbsbige/nattypetester Provides configuration paths and default STUN servers. ConfigDirectory points to the ApplicationData folder under NatTypeTester, ConfigFilePath is the config.json path, and DefaultStunServers lists eight public STUN servers. ```csharp public static class ConfigurationConsts { private const string ConfigFileName = "config.json"; public static string ConfigDirectory => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), nameof(NatTypeTester)); public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName); public static readonly ImmutableArray DefaultStunServers = [ "stun.fitauto.ru", "stun.m-online.net", "stun.mixvoip.com", "stun.voipgate.com", "stun.t-online.de", "stun.srce.hr", "stun.aa.net.uk", "stun.miwifi.com" ]; } ``` -------------------------------- ### MappingBehaviorTestAsync Source: https://github.com/hmbsbige/nattypetester Runs the mapping behavior test and publishes each step to the State property. ```csharp public ValueTask MappingBehaviorTestAsync(CancellationToken cancellationToken = default); ``` -------------------------------- ### StunClient3489 Constructor Source: https://github.com/hmbsbige/nattypetester Initializes a new instance of the StunClient3489 class with the specified STUN server endpoint, local endpoint, optional UDP proxy, and ownership flag. ```APIDOC ## StunClient3489 Constructor ### Description Initializes a new instance of the StunClient3489 class. ### Method Constructor ### Parameters - **server** (IPEndPoint) - Required - STUN server endpoint to query. - **local** (IPEndPoint) - Required - Local endpoint to bind to (address family must match the server). - **proxy** (IUdpProxy?) - Optional - UDP proxy; when null, a NoneUdpProxy(local) is created. - **ownedProxy** (bool) - Optional - Whether this client owns (and disposes) the proxy. Default: true. ### Response No return value. ``` -------------------------------- ### Stun5389NatBehaviorDiscovery Constructor Source: https://github.com/hmbsbige/nattypetester Initializes a new instance of the Stun5389NatBehaviorDiscovery class with the specified STUN server endpoint. ```APIDOC ## Constructor ### Description Creates a new STUN 5389 NAT behavior discovery instance for the given server. ### Signature ```csharp public Stun5389NatBehaviorDiscovery(IPEndPoint server) ``` ### Parameters - **server** (IPEndPoint) - Required - The STUN server endpoint to query. ``` -------------------------------- ### StunClient5389UDP Constructor Source: https://github.com/hmbsbige/nattypetester Initializes a new instance of the StunClient5389UDP class with the specified server and local endpoints, and optional UDP proxy. ```csharp public StunClient5389UDP(IPEndPoint server, IPEndPoint local, IUdpProxy? proxy = default, bool ownedProxy = true); ``` -------------------------------- ### BindingTestAsync Source: https://github.com/hmbsbige/nattypetester Performs a binding test and returns the result object. ```APIDOC ## BindingTestAsync ### Description Runs a binding test and returns the result. ### Method ValueTask ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Returns ValueTask - The result of the binding test. ### Example ```csharp StunResult5389 result = await client.BindingTestAsync(); Console.WriteLine(result.PublicEndPoint); ``` ``` -------------------------------- ### StunTestInputResolver class declaration Source: https://github.com/hmbsbige/nattypetester Internal class that resolves STUN test inputs. Constructor takes an IServiceProvider. Provides static and instance methods for parsing STUN servers, resolving input options, and querying with a proxy. Throws ArgumentException with messages from NatTypeTesterLanguage.Current for various error conditions. ```csharp internal class StunTestInputResolver(IServiceProvider serviceProvider) { public static StunServer ParseStunServer(string stunServer, ushort defaultPort = StunServer.DefaultPort); public async Task<(Socks5CreateOption? Socks5Option, IPAddress ServerIp, IPEndPoint LocalEndPoint)> ResolveAsync(StunTestInput input, StunServer server, CancellationToken cancellationToken = default); public static Task QueryWithProxyAsync(IUdpStunClient client, CancellationToken cancellationToken = default); } ``` -------------------------------- ### StunTestInput DTO Source: https://github.com/hmbsbige/nattypetester Input DTO for STUN tests. Requires StunServer (host[:port]) parsed by StunServer.TryParse, throws ArgumentException when invalid. Proxy defaults to Plain, LocalEndPoint null/empty binds wildcard per address family, SkipCertificateValidation defaults to false. ```csharp public sealed class StunTestInput { public required string StunServer { get; init; } public ProxyOptions Proxy { get; init; } = new(); public string? LocalEndPoint { get; init; } public bool SkipCertificateValidation { get; init; } } ``` -------------------------------- ### ILauncherService Source: https://github.com/hmbsbige/nattypetester Service interface for launching a URI on the platform shell. Used to open external links or resources. ```APIDOC ## ILauncherService ### Description Service interface for launching a URI on the platform shell. Used to open external links or resources. ### Members #### LaunchUriAsync - **Signature**: `ValueTask LaunchUriAsync(Uri uri)` - **Description**: Launches a URI on the platform shell (Avalonia `TopLevel.Launcher` in the desktop implementation). ##### Parameters - **uri** (`Uri`) - Required - The URI to launch. ``` -------------------------------- ### Parse response key attributes with AttributeExtensions Source: https://github.com/hmbsbige/nattypetester Parses rawBytes into a StunMessage5389 and prints the XOR-mapped and other address attributes. Uses GetXorMappedAddressAttribute (falls back to MappedAddress) and GetOtherAddressAttribute (falls back to ChangedAddress); both return null when no matching attribute is present. ```csharp using STUN.Messages; using STUN.Utils; StunMessage5389 response = new(); if (!response.TryParse(rawBytes)) { return; } Console.WriteLine(response.GetXorMappedAddressAttribute()); Console.WriteLine(response.GetOtherAddressAttribute()); ``` -------------------------------- ### ITcpProxy.ConnectAsync Source: https://github.com/hmbsbige/nattypetester Connects from a local endpoint to a destination endpoint, returning a bidirectional pipe for communication. ```APIDOC ## ConnectAsync ### Description Connects from a local endpoint to a destination endpoint, returning a bidirectional pipe for communication. ### Method ConnectAsync ### Signature ValueTask ConnectAsync(IPEndPoint local, IPEndPoint dst, CancellationToken cancellationToken = default) ### Parameters - **local** (IPEndPoint) - Required - Local endpoint. - **dst** (IPEndPoint) - Required - Destination endpoint. - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Response - **ValueTask** - A bidirectional pipe for communication. ``` -------------------------------- ### TlsOverSocks5Proxy Source: https://github.com/hmbsbige/nattypetester A TLS over SOCKS5 proxy that connects through SOCKS5 first, then performs the same TLS handshake as TlsProxy. The primary constructor parameters are socks5Options, targetHost, and skipCertificateValidation. ```APIDOC ## TlsOverSocks5Proxy ### Description Connects through SOCKS5 first, then runs the same TLS handshake (`SslStream(pipe.AsStream(true))`) as `TlsProxy`. ### Constructor Parameters - `socks5Options` (Socks5CreateOption) - Required - SOCKS5 options. - `targetHost` (string) - Required - TLS SNI host name. - `skipCertificateValidation` (bool) - Optional - When `true`, uses `RemoteCertificateValidationCallback` that disposes the chain (`CertificateChainDisposer`) and returns `true`. ### Members - `public override ValueTask ConnectAsync(IPEndPoint local, IPEndPoint dst, CancellationToken cancellationToken = default);` - `protected override void CloseClient();` ``` -------------------------------- ### MappingBehaviorTestAsync Source: https://github.com/hmbsbige/nattypetester Runs the mapping behavior test and publishes the result to the State property. ```APIDOC ## MappingBehaviorTestAsync ### Description Executes the mapping behavior test and updates the `State` property. ### Method ValueTask ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Returns ValueTask ``` -------------------------------- ### StunServer Class Source: https://github.com/hmbsbige/nattypetester Represents a STUN server with a hostname and port. Provides a default constructor, a static TryParse method, and a ToString override. ```APIDOC ## StunServer Class ### Description Represents a STUN server with a hostname and port. Provides a default constructor, a static TryParse method, and a ToString override. ### Members - **Hostname** (string) - Hostname or IP address. - **Port** (ushort) - Port. - **DefaultPort** (ushort, const) - 3478 (RFC 5389). - **DefaultTlsPort** (ushort, const) - 5349 (RFC 5389 STUN-over-TLS). ### Constructors - **StunServer()** - Initializes a new instance with hostname "stun.syncthing.net" and port 3478. ### Methods - **TryParse(string s, out StunServer? result, ushort defaultPort = DefaultPort)** (static) - Parses a string into a StunServer instance. Returns true if successful; otherwise false. - **ToString()** - Returns a string representation, omitting the port when it equals DefaultPort and bracketing IPv6 hostnames. ### Example ```csharp using STUN; if (StunServer.TryParse("stun.example.com:5349", out StunServer? server, StunServer.DefaultTlsPort)) { Console.WriteLine(server); // "stun.example.com:5349" } ``` ``` -------------------------------- ### BindingTestAsync Source: https://github.com/hmbsbige/nattypetester Runs the binding test and returns the resulting StunResult5389 directly. Does not modify the State property. ```csharp public ValueTask BindingTestAsync(CancellationToken cancellationToken = default); ``` -------------------------------- ### StunServer class definition Source: https://github.com/hmbsbige/nattypetester Public class with Hostname and Port properties, default ports 3478 and 5349, a default constructor using stun.syncthing.net:3478, and a TryParse method that delegates to HostnameEndpoint.TryParse. ToString omits the port when it equals DefaultPort and brackets IPv6 hostnames. Instances are only obtained via TryParse or the default constructor because the parameterized constructor is private. ```csharp public class StunServer { public string Hostname { get; } public ushort Port { get; } public const ushort DefaultPort = 3478; public const ushort DefaultTlsPort = 5349; public StunServer(); // hostname "stun.syncthing.net", port 3478 public static bool TryParse(string s, [NotNullWhen(true)] out StunServer? result, ushort defaultPort = DefaultPort); public override string ToString(); } ``` -------------------------------- ### HostnameEndpoint.TryParse Source: https://github.com/hmbsbige/nattypetester Parses a hostname string into a HostnameEndpoint object. Accepts formats like "hostname", "hostname:port", "ip:port", and "[ipv6]:port". Returns false for empty input or invalid hostnames. ```APIDOC ## HostnameEndpoint.TryParse ### Description Parses a hostname string into a HostnameEndpoint object. Accepts formats like "hostname", "hostname:port", "ip:port", and "[ipv6]:port". Returns false for empty input or invalid hostnames. ### Method TryParse ### Signature public static bool TryParse(string s, [NotNullWhen(true)] out HostnameEndpoint? result, ushort defaultPort = 0); ### Parameters - **s** (string) - Required - The string to parse. - **result** (out HostnameEndpoint?) - Required - The parsed endpoint, or null if parsing fails. - **defaultPort** (ushort) - Optional - Default port to use if the string omits it. Defaults to 0. ### Returns - **bool** - True if parsing succeeded, false otherwise. ### Remarks Accepted formats: "hostname", "hostname:port", "ip:port", "[ipv6]:port". The last ':' after a closing ']' or the last single ':' splits host/port; the host portion must pass Uri.CheckHostName as Dns, IPv4, or IPv6. A missing or unparsable port falls back to defaultPort. Empty input returns false. ToString() brackets IPv6. ### Request Example ```csharp using STUN; HostnameEndpoint.TryParse("[2001:db8::1]:5349", out HostnameEndpoint? endPoint); Console.WriteLine(endPoint?.ToString()); // "[2001:db8::1]:5349" ``` ``` -------------------------------- ### IStunClient.QueryAsync Source: https://github.com/hmbsbige/nattypetester Performs a full STUN query to discover NAT characteristics. Cancellation-safe; a timed-out request step is treated as a null response by the underlying implementation rather than an exception. ```APIDOC ## QueryAsync ### Description Performs a full STUN query to discover NAT characteristics. Cancellation-safe; a timed-out request step is treated as a `null` response by the underlying implementation rather than an exception. ### Method ValueTask ### Signature ```csharp ValueTask QueryAsync(CancellationToken cancellationToken = default); ``` ### Parameters - `cancellationToken` (CancellationToken) - Optional - Cancellation token to cancel the operation. ``` -------------------------------- ### FilteringBehaviorTestAsync Source: https://github.com/hmbsbige/nattypetester Always throws NotSupportedException because filtering tests apply only to UDP. ```APIDOC ## FilteringBehaviorTestAsync ### Description This method is not supported for TCP clients and always throws a `NotSupportedException`. ### Method ValueTask ### Parameters - **cancellationToken** (CancellationToken) - Optional - Cancellation token. ### Throws - **NotSupportedException** - Always thrown with message "Filtering test applies only to UDP." ``` -------------------------------- ### CreateFilteringBehaviorTest Method Source: https://github.com/hmbsbige/nattypetester Creates a discovery action that performs the binding test followed by filtering behavior tests. ```APIDOC ## CreateFilteringBehaviorTest ### Description Creates a discovery action for the binding test, then only filtering tests. ### Method CreateFilteringBehaviorTest ### Signature ```csharp public StunDiscoveryAction CreateFilteringBehaviorTest(); ``` ### Returns - **StunDiscoveryAction** - The action to execute for filtering behavior discovery. ``` -------------------------------- ### AppHttpClientFactory internal static class Source: https://github.com/hmbsbige/nattypetester Defines the internal static factory with a Create method that returns an HttpClient. When proxyOptions.Type is Socks5 and the server parses (default port NatTypeTesterConsts.DefaultSocks5Port = 1080), it builds a SocketsHttpHandler with a WebProxy and credentials if username is non-blank; otherwise returns httpClientFactory.CreateClient(). ```csharp internal static class AppHttpClientFactory { public static HttpClient Create(IHttpClientFactory httpClientFactory, ProxyOptions proxyOptions); } ``` -------------------------------- ### Stun5389NatBehaviorDiscovery class definition Source: https://github.com/hmbsbige/nattypetester Public API for the RFC 5780 §4.2 STUN NAT behavior discovery machine. Constructor takes the STUN server endpoint. Methods create discovery actions for binding, mapping, and filtering tests; GotResponse processes a STUN response and returns the next action or null when done. ```csharp /// The STUN server endpoint to query. public class Stun5389NatBehaviorDiscovery(IPEndPoint server) { public StunResult5389 Result { get; } = new(); public StunDiscoveryAction CreateQuery(); public StunDiscoveryAction CreateBindingTest(); public StunDiscoveryAction CreateMappingBehaviorTest(); public StunDiscoveryAction CreateFilteringBehaviorTest(); /// The STUN response received, or if the request timed out. public StunDiscoveryAction? GotResponse(StunResponse? response); } ``` -------------------------------- ### SettingsViewModel class with ApplyConfig Source: https://github.com/hmbsbige/nattypetester Root view model exposing four sub-view models and an idempotent ApplyConfig that fans out to them in order. ```csharp public partial class SettingsViewModel : ViewModelBase { public ApplicationSettingsViewModel Application { get; } public ConnectionSettingsViewModel Connection { get; } public StunServerSettingsViewModel StunServer { get; } public UpdateSettingsViewModel Update { get; } [Reactive] public partial bool IsInitialized { get; private set; } public void ApplyConfig(AppConfig config); } ``` -------------------------------- ### StunServerSettingsViewModel class definition Source: https://github.com/hmbsbige/nattypetester View model for STUN server settings with reactive properties for the server list, current server, list URI, and initialization state. Generated commands handle adding, deleting, and loading STUN servers; ApplyConfig replaces the list and registers persistence for the current server and list URI. ```csharp public partial class StunServerSettingsViewModel : ViewModelBase { [Reactive] public partial ObservableCollection StunServers { get; private set; } = []; [Reactive] public partial string CurrentStunServer { get; set; } = string.Empty; [Reactive] public partial string? StunServerListUri { get; set; } [Reactive] public partial bool IsInitialized { get; private set; } } ``` -------------------------------- ### FilteringBehaviorTestAsync Source: https://github.com/hmbsbige/nattypetester Runs the filtering behavior test and publishes each step to the State property. ```csharp public ValueTask FilteringBehaviorTestAsync(CancellationToken cancellationToken = default); ``` -------------------------------- ### Build STUN attribute by hand with StunAttribute.WriteTo Source: https://github.com/hmbsbige/nattypetester Shows how to construct a MappedAddress attribute manually by setting Type, Length, and Value, then let StunAttribute.WriteTo validate consistency. Uses MappedAddressStunAttributeValue with IPv4 family, address 192.0.2.1, and port 5000; Length is 8 (4 + 4 bytes IPv4). ```csharp using STUN.Enums; using STUN.Messages; using STUN.Messages.StunAttributeValues; StunAttribute mapped = new() { Type = AttributeType.MappedAddress, Length = 8, // 4 + 4 bytes IPv4 Value = new MappedAddressStunAttributeValue { Family = IpFamily.IPv4, Address = System.Net.IPAddress.Parse("192.0.2.1"), Port = 5000 } }; byte[] raw = new byte[mapped.RealLength]; int written = mapped.WriteTo(raw); ``` -------------------------------- ### StunClient5389TCP Constructor Source: https://github.com/hmbsbige/nattypetester Initializes a new instance of the StunClient5389TCP class with the specified STUN server endpoint, local endpoint, optional TCP proxy, and proxy ownership flag. ```APIDOC ## Constructor ### Description Creates a new STUN client for TCP/TLS connections. ### Parameters - **server** (IPEndPoint) - Required - STUN server endpoint. - **local** (IPEndPoint) - Required - Local endpoint to bind. - **proxy** (ITcpProxy?) - Optional - TCP proxy; defaults to a new `DirectTcpProxy()`. - **ownedProxy** (bool) - Optional - Whether the client disposes the proxy. Default is `true`. ### Example ```csharp StunClient5389TCP client = new( IPEndPoint.Parse("203.0.113.10:3478"), new IPEndPoint(IPAddress.Any, 0)); ``` ``` -------------------------------- ### Basic full query with StunClient3489 Source: https://github.com/hmbsbige/nattypetester Performs a complete RFC 3489 NAT type discovery against a STUN server. The client binds to an ephemeral local endpoint (IPAddress.Any, port 0) and uses the default no-proxy behavior. After QueryAsync completes, State.NatType and State.PublicEndPoint contain the discovered values. ```csharp using STUN.Client; using System.Net; IPEndPoint server = IPEndPoint.Parse("203.0.113.10:3478"); await using StunClient3489 client = new(server, new IPEndPoint(IPAddress.Any, 0)); await client.QueryAsync(); Console.WriteLine($"NAT type: {client.State.NatType}"); Console.WriteLine($"Public end point: {client.State.PublicEndPoint}"); ```