├── .editorconfig ├── .github ├── renovate.json └── workflows │ └── CI.yaml ├── .gitignore ├── Directory.Build.props ├── Directory.Packages.props ├── LICENSE ├── NatTypeTester.slnx ├── NuGet.Config ├── README.md ├── docs └── img │ ├── RFC3489.png │ ├── RFC5780_4.2.png │ ├── RFC5780_4.3.png │ ├── RFC5780_4.4.png │ └── RFC5780_4.5.png ├── scripts ├── DotNetDllPathPatcher.ps1 └── build.ps1 └── src ├── NatTypeTester.Models ├── Config.cs ├── NatTypeTester.Models.csproj └── NatTypeTesterModelsModule.cs ├── NatTypeTester.ViewModels ├── MainWindowViewModel.cs ├── NatTypeTester.ViewModels.csproj ├── NatTypeTesterViewModelModule.cs ├── RFC3489ViewModel.cs ├── RFC5780ViewModel.cs ├── SettingViewModel.cs ├── ValueConverters │ └── StringToIPEndpointTypeConverter.cs └── ViewModelBase.cs ├── NatTypeTester ├── App.xaml ├── App.xaml.cs ├── Dialogs │ └── DisposableContentDialog.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── NatTypeTester.csproj ├── NatTypeTesterModule.cs ├── Properties │ └── DesignTimeResources.xaml ├── Utils │ └── Extensions.cs ├── Views │ ├── RFC3489View.xaml │ ├── RFC3489View.xaml.cs │ ├── RFC5780View.xaml │ ├── RFC5780View.xaml.cs │ ├── SettingView.xaml │ └── SettingView.xaml.cs ├── app.manifest └── icon.ico ├── STUN ├── Client │ ├── IStunClient.cs │ ├── IStunClient5389.cs │ ├── IUdpStunClient.cs │ ├── StunClient3489.cs │ ├── StunClient5389TCP.cs │ └── StunClient5389UDP.cs ├── Enums │ ├── AttributeType.cs │ ├── BindingTestResult.cs │ ├── Class.cs │ ├── FilteringBehavior.cs │ ├── IpFamily.cs │ ├── MappingBehavior.cs │ ├── Method.cs │ ├── NatType.cs │ ├── ProxyType.cs │ ├── StunMessageType.cs │ └── TransportType.cs ├── HostnameEndpoint.cs ├── Messages │ ├── StunAttribute.cs │ ├── StunAttributeValues │ │ ├── AddressStunAttributeValue.cs │ │ ├── ChangeRequestStunAttributeValue.cs │ │ ├── ChangedAddressStunAttributeValue.cs │ │ ├── ErrorCodeStunAttributeValue.cs │ │ ├── IStunAttributeValue.cs │ │ ├── MappedAddressStunAttributeValue.cs │ │ ├── OtherAddressStunAttributeValue.cs │ │ ├── ReflectedFromStunAttributeValue.cs │ │ ├── ResponseAddressStunAttributeValue.cs │ │ ├── SourceAddressStunAttributeValue.cs │ │ ├── UnknownStunAttributeValue.cs │ │ ├── UselessStunAttributeValue.cs │ │ └── XorMappedAddressStunAttributeValue.cs │ ├── StunMessage5389.cs │ └── StunResponse.cs ├── Proxy │ ├── DirectTcpProxy.cs │ ├── ITcpProxy.cs │ ├── IUdpProxy.cs │ ├── NoneUdpProxy.cs │ ├── ProxyFactory.cs │ ├── Socks5TcpProxy.cs │ ├── Socks5UdpProxy.cs │ ├── TlsOverSocks5Proxy.cs │ └── TlsProxy.cs ├── STUN.csproj ├── StunResult │ ├── ClassicStunResult.cs │ ├── StunResult.cs │ └── StunResult5389.cs ├── StunServer.cs └── Utils │ └── AttributeExtensions.cs └── tests └── UnitTest ├── HostnameEndpointTest.cs ├── StunClien5389UDPTest.cs ├── StunClient3489Test.cs ├── StunClient5389TCPTest.cs ├── UnitTest.csproj └── XorMappedTest.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | # 如果要从更高级别的目录继承 .editorconfig 设置,请删除以下行 2 | root = true 3 | 4 | [*] 5 | # 字符集 6 | charset = utf-8 7 | 8 | # 新行首选项 9 | end_of_line = lf 10 | insert_final_newline = true 11 | 12 | # ReSharper properties 13 | resharper_blank_lines_around_single_line_auto_property = 1 14 | resharper_blank_lines_before_block_statements = 1 15 | resharper_braces_for_ifelse = not_required 16 | resharper_braces_redundant = false 17 | resharper_csharp_alignment_tab_fill_style = use_tabs_only 18 | resharper_csharp_indent_style = tab 19 | resharper_csharp_insert_final_newline = true 20 | resharper_csharp_keep_existing_enum_arrangement = false 21 | resharper_csharp_space_before_trailing_comment = false 22 | resharper_csharp_wrap_arguments_style = chop_if_long 23 | resharper_csharp_wrap_lines = false 24 | resharper_for_simple_types = use_explicit_type 25 | resharper_fsharp_insert_final_newline = false 26 | resharper_html_insert_final_newline = false 27 | resharper_instance_members_qualify_declared_in = 28 | resharper_keep_existing_initializer_arrangement = false 29 | resharper_max_initializer_elements_on_line = 1 30 | resharper_place_accessorholder_attribute_on_same_line = false 31 | resharper_place_expr_property_on_single_line = true 32 | resharper_place_field_attribute_on_same_line = false 33 | resharper_resx_insert_final_newline = false 34 | resharper_shaderlab_insert_final_newline = false 35 | resharper_space_within_single_line_array_initializer_braces = true 36 | resharper_t4_insert_final_newline = false 37 | resharper_vb_insert_final_newline = false 38 | resharper_wrap_object_and_collection_initializer_style = wrap_if_long 39 | resharper_xmldoc_indent_text = ZeroIndent 40 | resharper_xmldoc_insert_final_newline = false 41 | resharper_xml_insert_final_newline = false 42 | 43 | [*.csproj] 44 | indent_size = 2 45 | 46 | [*.props] 47 | indent_size = 2 48 | 49 | # c# 文件 50 | [*.cs] 51 | 52 | # 缩进和间距 53 | indent_size = 4 54 | indent_style = tab 55 | tab_width = 4 56 | 57 | #### .NET 编码约定 #### 58 | 59 | # 组织 Using 60 | dotnet_separate_import_directive_groups = false 61 | dotnet_sort_system_directives_first = false 62 | file_header_template = unset 63 | 64 | # this. 和 Me. 首选项 65 | dotnet_style_qualification_for_event = false:suggestion 66 | dotnet_style_qualification_for_field = false 67 | dotnet_style_qualification_for_method = false:suggestion 68 | dotnet_style_qualification_for_property = false:suggestion 69 | 70 | # 语言关键字与 bcl 类型首选项 71 | dotnet_style_predefined_type_for_locals_parameters_members = true:warning 72 | dotnet_style_predefined_type_for_member_access = true:warning 73 | 74 | # 括号首选项 75 | dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary 76 | dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary 77 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning 78 | dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary 79 | 80 | # 修饰符首选项 81 | dotnet_style_require_accessibility_modifiers = for_non_interface_members 82 | 83 | # 表达式级首选项 84 | dotnet_style_coalesce_expression = true:warning 85 | dotnet_style_collection_initializer = true 86 | dotnet_style_explicit_tuple_names = true:warning 87 | dotnet_style_namespace_match_folder = true 88 | dotnet_style_null_propagation = true:warning 89 | dotnet_style_object_initializer = true 90 | dotnet_style_operator_placement_when_wrapping = beginning_of_line 91 | dotnet_style_prefer_auto_properties = true:warning 92 | dotnet_style_prefer_compound_assignment = true:warning 93 | dotnet_style_prefer_conditional_expression_over_assignment = true 94 | dotnet_style_prefer_conditional_expression_over_return = true 95 | dotnet_style_prefer_inferred_anonymous_type_member_names = true 96 | dotnet_style_prefer_inferred_tuple_names = true 97 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning 98 | dotnet_style_prefer_simplified_boolean_expressions = true:warning 99 | dotnet_style_prefer_simplified_interpolation = true 100 | 101 | # 字段首选项 102 | dotnet_style_readonly_field = true 103 | 104 | # 参数首选项 105 | dotnet_code_quality_unused_parameters = all 106 | 107 | # 禁止显示首选项 108 | dotnet_remove_unnecessary_suppression_exclusions = 0 109 | 110 | # 新行首选项 111 | dotnet_style_allow_multiple_blank_lines_experimental = false 112 | dotnet_style_allow_statement_immediately_after_block_experimental = true 113 | 114 | #### c# 编码约定 #### 115 | 116 | # var 首选项 117 | csharp_style_var_elsewhere = false:suggestion 118 | csharp_style_var_for_built_in_types = false:suggestion 119 | csharp_style_var_when_type_is_apparent = false:suggestion 120 | 121 | # Expression-bodied 成员 122 | csharp_style_expression_bodied_accessors = true:suggestion 123 | csharp_style_expression_bodied_constructors = false:warning 124 | csharp_style_expression_bodied_indexers = true:suggestion 125 | csharp_style_expression_bodied_lambdas = true:suggestion 126 | csharp_style_expression_bodied_local_functions = false:warning 127 | csharp_style_expression_bodied_methods = false:warning 128 | csharp_style_expression_bodied_operators = false:warning 129 | csharp_style_expression_bodied_properties = true:suggestion 130 | 131 | # 模式匹配首选项 132 | csharp_style_pattern_matching_over_as_with_null_check = true:warning 133 | csharp_style_pattern_matching_over_is_with_cast_check = true:warning 134 | csharp_style_prefer_not_pattern = true:warning 135 | csharp_style_prefer_pattern_matching = true:warning 136 | csharp_style_prefer_switch_expression = true:warning 137 | 138 | # Null 检查首选项 139 | csharp_style_conditional_delegate_call = true 140 | 141 | # 修饰符首选项 142 | csharp_prefer_static_local_function = true 143 | csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async 144 | 145 | # 代码块首选项 146 | csharp_prefer_braces = true:suggestion 147 | csharp_prefer_simple_using_statement = true:warning 148 | csharp_style_namespace_declarations = file_scoped:warning 149 | 150 | # 表达式级首选项 151 | csharp_prefer_simple_default_expression = true:warning 152 | csharp_style_deconstructed_variable_declaration = true 153 | csharp_style_implicit_object_creation_when_type_is_apparent = true:warning 154 | csharp_style_inlined_variable_declaration = true:warning 155 | csharp_style_pattern_local_over_anonymous_function = true 156 | csharp_style_prefer_index_operator = true:warning 157 | csharp_style_prefer_null_check_over_type_check = true:warning 158 | csharp_style_prefer_range_operator = false:none 159 | csharp_style_throw_expression = true 160 | csharp_style_unused_value_assignment_preference = discard_variable 161 | csharp_style_unused_value_expression_statement_preference = discard_variable 162 | 163 | # "using" 指令首选项 164 | csharp_using_directive_placement = outside_namespace:warning 165 | 166 | # 新行首选项 167 | csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true 168 | csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false 169 | csharp_style_allow_embedded_statements_on_same_line_experimental = true 170 | 171 | #### C# 格式规则 #### 172 | 173 | # 新行首选项 174 | csharp_new_line_before_catch = true 175 | csharp_new_line_before_else = true 176 | csharp_new_line_before_finally = true 177 | csharp_new_line_before_members_in_anonymous_types = true 178 | csharp_new_line_before_members_in_object_initializers = true 179 | csharp_new_line_before_open_brace = all 180 | csharp_new_line_between_query_expression_clauses = true 181 | 182 | # 缩进首选项 183 | csharp_indent_block_contents = true 184 | csharp_indent_braces = false 185 | csharp_indent_case_contents = true 186 | csharp_indent_case_contents_when_block = false 187 | csharp_indent_labels = one_less_than_current 188 | csharp_indent_switch_labels = true 189 | 190 | # 空格键首选项 191 | csharp_space_after_cast = false 192 | csharp_space_after_colon_in_inheritance_clause = true 193 | csharp_space_after_comma = true 194 | csharp_space_after_dot = false 195 | csharp_space_after_keywords_in_control_flow_statements = true 196 | csharp_space_after_semicolon_in_for_statement = true 197 | csharp_space_around_binary_operators = before_and_after 198 | csharp_space_around_declaration_statements = false 199 | csharp_space_before_colon_in_inheritance_clause = true 200 | csharp_space_before_comma = false 201 | csharp_space_before_dot = false 202 | csharp_space_before_open_square_brackets = false 203 | csharp_space_before_semicolon_in_for_statement = false 204 | csharp_space_between_empty_square_brackets = false 205 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 206 | csharp_space_between_method_call_name_and_opening_parenthesis = false 207 | csharp_space_between_method_call_parameter_list_parentheses = false 208 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 209 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 210 | csharp_space_between_method_declaration_parameter_list_parentheses = false 211 | csharp_space_between_parentheses = false 212 | csharp_space_between_square_brackets = false 213 | 214 | # 包装首选项 215 | csharp_preserve_single_line_blocks = true 216 | csharp_preserve_single_line_statements = false 217 | 218 | #### 命名样式 #### 219 | 220 | # 命名规则 221 | 222 | dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion 223 | dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface 224 | dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i 225 | 226 | dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion 227 | dotnet_naming_rule.types_should_be_pascal_case.symbols = types 228 | dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case 229 | 230 | dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion 231 | dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members 232 | dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case 233 | 234 | # 符号规范 235 | 236 | dotnet_naming_symbols.interface.applicable_kinds = interface 237 | dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 238 | dotnet_naming_symbols.interface.required_modifiers = 239 | 240 | dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum 241 | dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 242 | dotnet_naming_symbols.types.required_modifiers = 243 | 244 | dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method 245 | dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 246 | dotnet_naming_symbols.non_field_members.required_modifiers = 247 | 248 | # 命名样式 249 | 250 | dotnet_naming_style.pascal_case.required_prefix = 251 | dotnet_naming_style.pascal_case.required_suffix = 252 | dotnet_naming_style.pascal_case.word_separator = 253 | dotnet_naming_style.pascal_case.capitalization = pascal_case 254 | 255 | dotnet_naming_style.begins_with_i.required_prefix = I 256 | dotnet_naming_style.begins_with_i.required_suffix = 257 | dotnet_naming_style.begins_with_i.word_separator = 258 | dotnet_naming_style.begins_with_i.capitalization = pascal_case 259 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "assignees": [ 4 | "HMBSbige" 5 | ], 6 | "dependencyDashboard": false, 7 | "extends": [ 8 | "config:recommended", 9 | ":configMigration", 10 | ":automergeBranch", 11 | ":automergeDigest", 12 | ":automergeMinor", 13 | ":disableRateLimiting" 14 | ], 15 | "packageRules": [ 16 | { 17 | "matchSourceUrls": [ 18 | "https://github.com/abpframework/abp" 19 | ], 20 | "groupName": "abp" 21 | }, 22 | { 23 | "matchSourceUrls": [ 24 | "https://github.com/reactiveui/ReactiveUI" 25 | ], 26 | "groupName": "ReactiveUI" 27 | } 28 | ], 29 | "labels": [ 30 | "Automatic" 31 | ] 32 | } -------------------------------------------------------------------------------- /.github/workflows/CI.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | env: 6 | ProjectName: ${{ github.event.repository.name }} 7 | NET_TFM: net8.0-windows10.0.22621.0 8 | Configuration: Release 9 | 10 | jobs: 11 | check_format: 12 | name: Check format 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-dotnet@v4 17 | with: 18 | dotnet-version: 9.0.x 19 | - run: dotnet format -v diag --verify-no-changes 20 | 21 | test: 22 | name: Run tests 23 | runs-on: ${{ matrix.os }} 24 | strategy: 25 | matrix: 26 | os: 27 | - windows-latest 28 | - ubuntu-latest 29 | - macos-latest 30 | 31 | steps: 32 | - uses: actions/checkout@v4 33 | - uses: actions/setup-dotnet@v4 34 | with: 35 | dotnet-version: 9.0.x 36 | - run: dotnet test -c Release 37 | 38 | build: 39 | needs: [test, check_format] 40 | runs-on: windows-latest 41 | steps: 42 | - uses: actions/checkout@v4 43 | - uses: actions/setup-dotnet@v4 44 | with: 45 | dotnet-version: 9.0.x 46 | 47 | - name: Build 48 | shell: pwsh 49 | run: | 50 | .\scripts\build.ps1 51 | 52 | - name: Upload 53 | uses: actions/upload-artifact@v4 54 | with: 55 | name: ${{ env.ProjectName }} 56 | path: src\${{ env.ProjectName }}\bin\${{ env.Configuration }}\${{ env.NET_TFM }}\generic\publish\ 57 | 58 | nuget: 59 | needs: [test, check_format] 60 | if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') }} 61 | runs-on: ubuntu-latest 62 | permissions: 63 | packages: write 64 | strategy: 65 | matrix: 66 | PackageName: 67 | - STUN 68 | 69 | steps: 70 | - uses: actions/checkout@v4 71 | - uses: actions/setup-dotnet@v4 72 | with: 73 | dotnet-version: 9.0.x 74 | 75 | - name: Build 76 | working-directory: src/${{ matrix.PackageName }} 77 | run: dotnet pack 78 | 79 | - name: Push nuget packages 80 | working-directory: src/${{ matrix.PackageName }}/bin/Release 81 | run: | 82 | dotnet nuget push *.nupkg -s https://nuget.pkg.github.com/HMBSbige -k ${{ secrets.GITHUB_TOKEN }} --skip-duplicate 83 | dotnet nuget push *.nupkg -s https://api.nuget.org/v3/index.json -k ${{ secrets.NuGetAPIKey }} --skip-duplicate 84 | 85 | release: 86 | needs: [build, nuget] 87 | runs-on: ubuntu-latest 88 | permissions: 89 | contents: write 90 | 91 | steps: 92 | - uses: actions/download-artifact@v4 93 | with: 94 | name: ${{ env.ProjectName }} 95 | path: ${{ env.ProjectName }} 96 | 97 | - name: Package 98 | shell: pwsh 99 | run: | 100 | New-Item -ItemType Directory -Path builtfiles -Force > $null 101 | $zip_path = "builtfiles/$env:ProjectName-${{ github.ref_name }}.7z" 102 | 7z a -mx9 "$zip_path" ${{ env.ProjectName }} 103 | echo "GENERIC_SHA256=$((Get-FileHash $zip_path -Algorithm SHA256).Hash)" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append 104 | 105 | - name: Create a new GitHub release 106 | uses: ncipollo/release-action@v1 107 | with: 108 | token: ${{ secrets.GITHUB_TOKEN }} 109 | prerelease: true 110 | draft: false 111 | artifacts: builtfiles/* 112 | body: | 113 | ## Hash 114 | | Filename | SHA-256 | 115 | | :- | :- | 116 | | ${{ env.ProjectName }}-${{ github.ref_name }}.7z | ${{ env.GENERIC_SHA256 }} | 117 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.vspscc 94 | *.vssscc 95 | .builds 96 | *.pidb 97 | *.svclog 98 | *.scc 99 | 100 | # Chutzpah Test files 101 | _Chutzpah* 102 | 103 | # Visual C++ cache files 104 | ipch/ 105 | *.aps 106 | *.ncb 107 | *.opendb 108 | *.opensdf 109 | *.sdf 110 | *.cachefile 111 | *.VC.db 112 | *.VC.VC.opendb 113 | 114 | # Visual Studio profiler 115 | *.psess 116 | *.vsp 117 | *.vspx 118 | *.sap 119 | 120 | # Visual Studio Trace Files 121 | *.e2e 122 | 123 | # TFS 2012 Local Workspace 124 | $tf/ 125 | 126 | # Guidance Automation Toolkit 127 | *.gpState 128 | 129 | # ReSharper is a .NET coding add-in 130 | _ReSharper*/ 131 | *.[Rr]e[Ss]harper 132 | *.DotSettings.user 133 | 134 | # TeamCity is a build add-in 135 | _TeamCity* 136 | 137 | # DotCover is a Code Coverage Tool 138 | *.dotCover 139 | 140 | # AxoCover is a Code Coverage Tool 141 | .axoCover/* 142 | !.axoCover/settings.json 143 | 144 | # Coverlet is a free, cross platform Code Coverage Tool 145 | coverage*.json 146 | coverage*.xml 147 | coverage*.info 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # Fody - auto-generated XML schema 362 | FodyWeavers.xsd 363 | 364 | # JetBrains Rider 365 | .idea/ 366 | *.sln.iml 367 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | net8.0 4 | enable 5 | latest 6 | enable 7 | HMBSbige 8 | 9 | 10 | -------------------------------------------------------------------------------- /Directory.Packages.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | true 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Bruce Wayne 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /NatTypeTester.slnx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NatTypeTester 2 | Channel | Status 3 | -|- 4 | CI | [![CI](https://github.com/HMBSbige/NatTypeTester/workflows/CI/badge.svg)](https://github.com/HMBSbige/NatTypeTester/actions) 5 | Stun.Net | [![NuGet.org](https://img.shields.io/nuget/v/Stun.Net.svg?logo=nuget)](https://www.nuget.org/packages/Stun.Net/) 6 | 7 | ## RFC 8 | 9 | * [RFC 3489](https://datatracker.ietf.org/doc/html/rfc3489) 10 | * [RFC 5780](https://datatracker.ietf.org/doc/html/rfc5780) 11 | * [RFC 8489](https://datatracker.ietf.org/doc/html/rfc8489) 12 | 13 | ## Internet Protocol 14 | 15 | - [x] IPv4 16 | - [x] IPv6 17 | 18 | ## Transmission Protocol 19 | 20 | - [x] UDP 21 | - [x] TCP 22 | - [x] TLS-over-TCP 23 | - [ ] DTLS-over-UDP 24 | 25 | ## RFC3489 26 |
27 | 28 | ![](docs/img/RFC3489.png) 29 |
30 | 31 | ## RFC5389 32 | ### Binding Test 33 |
34 | Checking for UDP Connectivity with the STUN Server 35 | 36 | ![](docs/img/RFC5780_4.2.png) 37 |
38 | 39 | ### Mapping Behavior 40 |
41 | Determining NAT Mapping Behavior 42 | 43 | ![](docs/img/RFC5780_4.3.png) 44 |
45 | 46 | ### Filtering Behavior 47 |
48 | Determining NAT Filtering Behavior 49 | 50 | ![](docs/img/RFC5780_4.4.png) 51 |
52 | 53 | ### Combining Tests 54 |
55 | 56 | ![](docs/img/RFC5780_4.5.png) 57 | 58 |
59 | -------------------------------------------------------------------------------- /docs/img/RFC3489.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMBSbige/NatTypeTester/b55bf4399984a2c7ee2512fe180d7cc96022b506/docs/img/RFC3489.png -------------------------------------------------------------------------------- /docs/img/RFC5780_4.2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMBSbige/NatTypeTester/b55bf4399984a2c7ee2512fe180d7cc96022b506/docs/img/RFC5780_4.2.png -------------------------------------------------------------------------------- /docs/img/RFC5780_4.3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMBSbige/NatTypeTester/b55bf4399984a2c7ee2512fe180d7cc96022b506/docs/img/RFC5780_4.3.png -------------------------------------------------------------------------------- /docs/img/RFC5780_4.4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMBSbige/NatTypeTester/b55bf4399984a2c7ee2512fe180d7cc96022b506/docs/img/RFC5780_4.4.png -------------------------------------------------------------------------------- /docs/img/RFC5780_4.5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HMBSbige/NatTypeTester/b55bf4399984a2c7ee2512fe180d7cc96022b506/docs/img/RFC5780_4.5.png -------------------------------------------------------------------------------- /scripts/DotNetDllPathPatcher.ps1: -------------------------------------------------------------------------------- 1 | using namespace System.IO 2 | using namespace System.Text 3 | 4 | param([string]$exe_path, [string]$target_path = 'bin') 5 | $ErrorActionPreference = 'Stop' 6 | #$DebugPreference = 'Continue' 7 | 8 | $exe_path = (Resolve-Path -Path $exe_path).Path 9 | 10 | Write-Host "Origin path: `"$exe_path`"" 11 | Write-Host "Target dll path: $target_path" 12 | 13 | $separator = '\' 14 | $max_path_length = 1024 15 | 16 | $exe_name = [Path]::GetFileName($exe_path) 17 | $dll_name = [Path]::ChangeExtension($exe_name, '.dll') 18 | Write-Debug "exe: $exe_name" 19 | Write-Debug "dll: $dll_name" 20 | 21 | function Update-Exe { 22 | $old_bytes = [Encoding]::UTF8.GetBytes("$dll_name`0") 23 | if ($old_bytes.Count -gt $max_path_length) { 24 | throw [PathTooLongException] 'old dll path is too long' 25 | } 26 | 27 | $new_dll_path = "$target_path$separator$dll_name" 28 | $new_bytes = [Encoding]::UTF8.GetBytes("$new_dll_path`0") 29 | Write-Host "Dll path Change to `"$new_dll_path`"" 30 | if ($new_bytes.Count -gt $max_path_length) { 31 | throw [PathTooLongException] 'new dll path is too long' 32 | } 33 | 34 | $bytes = [File]::ReadAllBytes($exe_path) 35 | $index = (Get-Content $exe_path -Raw -Encoding 28591).IndexOf("$dll_name`0") 36 | if ($index -lt 0) { 37 | throw [InvalidDataException] 'Could not find old dll path' 38 | } 39 | Write-Debug "Position: $index" 40 | $end_postion = $index + $($new_bytes.Count) 41 | $end_length = $bytes.Count - $end_postion 42 | if ($end_postion -gt $bytes.Count) { 43 | throw [PathTooLongException] 'new dll path is too long' 44 | } 45 | Write-Debug "End Position: $end_postion" 46 | Write-Debug "End Length: $end_length" 47 | 48 | $fs = [File]::OpenWrite($exe_path) 49 | try { 50 | $fs.Write($bytes, 0, $index) 51 | $fs.Write($new_bytes) 52 | $fs.Write($bytes, $end_postion, $end_length) 53 | } 54 | finally { 55 | $fs.Dispose(); 56 | } 57 | } 58 | 59 | function Move-Dll { 60 | $tmpbin = 'tmpbin' 61 | $dir = [Path]::GetDirectoryName($exe_path); 62 | $root = [Path]::GetDirectoryName($dir); 63 | Write-Debug "root path: $root" 64 | Write-Debug "dir path: $dir" 65 | 66 | Rename-Item $dir $tmpbin 67 | New-Item -ItemType Directory $dir > $null 68 | Move-Item $root\$tmpbin $dir 69 | Rename-Item $dir\$tmpbin $target_path 70 | Move-Item $dir\$target_path\$exe_name $dir 71 | } 72 | 73 | Update-Exe 74 | Move-Dll 75 | -------------------------------------------------------------------------------- /scripts/build.ps1: -------------------------------------------------------------------------------- 1 | $ErrorActionPreference = 'Stop' 2 | 3 | dotnet --info 4 | 5 | $proj = 'NatTypeTester' 6 | $exe = "$proj.exe" 7 | $net_tfm = 'net8.0-windows10.0.22621.0' 8 | $configuration = 'Release' 9 | $output_dir = "src\$proj\bin\$configuration" 10 | $proj_path = "src\$proj\$proj.csproj" 11 | $generic_outdir = "$output_dir\$net_tfm\generic" 12 | 13 | function Build-Generic { 14 | Write-Host 'Building generic' 15 | 16 | $outdir = $generic_outdir 17 | $publishDir = "$outdir\publish" 18 | 19 | Remove-Item $publishDir -Recurse -Force -Confirm:$false -ErrorAction Ignore 20 | 21 | dotnet publish -c $configuration -f $net_tfm $proj_path -o $publishDir 22 | if ($LASTEXITCODE) { exit $LASTEXITCODE } 23 | 24 | & "$PSScriptRoot\DotNetDllPathPatcher.ps1" "$publishDir\$exe" bin 25 | if ($LASTEXITCODE) { exit $LASTEXITCODE } 26 | 27 | Remove-Item "$publishDir\$exe" 28 | } 29 | 30 | function Build { 31 | param([string]$arch) 32 | 33 | $rid = "win-$arch" 34 | Write-Host "Building $rid" 35 | 36 | $outdir = "$output_dir\$net_tfm\$rid" 37 | $publishDir = "$outdir\publish" 38 | 39 | Remove-Item $publishDir -Recurse -Force -Confirm:$false -ErrorAction Ignore 40 | 41 | dotnet publish -c $configuration -f $net_tfm -r $rid --no-self-contained true $proj_path 42 | if ($LASTEXITCODE) { exit $LASTEXITCODE } 43 | 44 | & "$PSScriptRoot\DotNetDllPathPatcher.ps1" "$publishDir\$exe" bin 45 | if ($LASTEXITCODE) { exit $LASTEXITCODE } 46 | 47 | Move-Item "$publishDir\$exe" "$generic_outdir\publish\$proj-$arch.exe" 48 | } 49 | 50 | Build-Generic 51 | Build x64 52 | Build x86 53 | Build arm64 54 | -------------------------------------------------------------------------------- /src/NatTypeTester.Models/Config.cs: -------------------------------------------------------------------------------- 1 | namespace NatTypeTester.Models; 2 | 3 | [UsedImplicitly] 4 | public sealed partial class Config : ReactiveObject, ISingletonDependency 5 | { 6 | public Config() 7 | { 8 | StunServer = @""; 9 | ProxyType = ProxyType.Plain; 10 | ProxyServer = @"127.0.0.1:1080"; 11 | } 12 | 13 | [Reactive] 14 | public partial string StunServer { get; set; } 15 | 16 | [Reactive] 17 | public partial ProxyType ProxyType { get; set; } 18 | 19 | [Reactive] 20 | public partial string ProxyServer { get; set; } 21 | 22 | [Reactive] 23 | public partial string? ProxyUser { get; set; } 24 | 25 | [Reactive] 26 | public partial string? ProxyPassword { get; set; } 27 | } 28 | -------------------------------------------------------------------------------- /src/NatTypeTester.Models/NatTypeTester.Models.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/NatTypeTester.Models/NatTypeTesterModelsModule.cs: -------------------------------------------------------------------------------- 1 | global using JetBrains.Annotations; 2 | global using ReactiveUI; 3 | global using ReactiveUI.SourceGenerators; 4 | global using STUN.Enums; 5 | global using Volo.Abp.DependencyInjection; 6 | global using Volo.Abp.Modularity; 7 | 8 | namespace NatTypeTester.Models; 9 | 10 | public class NatTypeTesterModelsModule : AbpModule; 11 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/MainWindowViewModel.cs: -------------------------------------------------------------------------------- 1 | using DynamicData; 2 | using DynamicData.Binding; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.VisualStudio.Threading; 5 | using NatTypeTester.Models; 6 | using ReactiveUI; 7 | using STUN; 8 | using System.Collections.Frozen; 9 | using System.Reactive.Linq; 10 | using Volo.Abp.DependencyInjection; 11 | 12 | namespace NatTypeTester.ViewModels; 13 | 14 | [ExposeServices( 15 | typeof(MainWindowViewModel), 16 | typeof(IScreen) 17 | )] 18 | public class MainWindowViewModel : ViewModelBase, IScreen 19 | { 20 | public RoutingState Router => TransientCachedServiceProvider.GetRequiredService(); 21 | 22 | public Config Config => TransientCachedServiceProvider.GetRequiredService(); 23 | 24 | private static readonly FrozenSet DefaultServers = 25 | [ 26 | @"stun.hot-chilli.net", 27 | @"stun.fitauto.ru", 28 | @"stun.internetcalls.com", 29 | @"stun.miwifi.com", 30 | @"stun.voip.aebc.com", 31 | @"stun.voipbuster.com", 32 | @"stun.voipstunt.com" 33 | ]; 34 | 35 | private SourceList List { get; } = new(); 36 | 37 | public readonly IObservableCollection StunServers = new ObservableCollectionExtended(); 38 | 39 | public MainWindowViewModel() 40 | { 41 | List.Connect() 42 | .DistinctValues(x => x) 43 | .ObserveOn(RxApp.MainThreadScheduler) 44 | .Bind(StunServers) 45 | .Subscribe(); 46 | } 47 | 48 | public void LoadStunServer() 49 | { 50 | foreach (string? server in DefaultServers) 51 | { 52 | List.Add(server); 53 | } 54 | 55 | Config.StunServer = DefaultServers.First(); 56 | 57 | Task.Run(() => 58 | { 59 | const string path = @"stun.txt"; 60 | 61 | if (!File.Exists(path)) 62 | { 63 | return; 64 | } 65 | 66 | foreach (string line in File.ReadLines(path)) 67 | { 68 | if (!string.IsNullOrWhiteSpace(line) && StunServer.TryParse(line, out StunServer? stun)) 69 | { 70 | List.Add(stun.ToString()); 71 | } 72 | } 73 | }).Forget(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/NatTypeTester.ViewModels.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/NatTypeTesterViewModelModule.cs: -------------------------------------------------------------------------------- 1 | using Dns.Net.Abstractions; 2 | using Dns.Net.Clients; 3 | using JetBrains.Annotations; 4 | using Microsoft.Extensions.DependencyInjection.Extensions; 5 | using NatTypeTester.Models; 6 | using Volo.Abp.Modularity; 7 | 8 | namespace NatTypeTester.ViewModels; 9 | 10 | [DependsOn(typeof(NatTypeTesterModelsModule))] 11 | [UsedImplicitly] 12 | public class NatTypeTesterViewModelModule : AbpModule 13 | { 14 | public override void ConfigureServices(ServiceConfigurationContext context) 15 | { 16 | context.Services.TryAddTransient(); 17 | context.Services.TryAddTransient(); 18 | context.Services.TryAddTransient(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/RFC3489ViewModel.cs: -------------------------------------------------------------------------------- 1 | using Dns.Net.Abstractions; 2 | using Dns.Net.Clients; 3 | using JetBrains.Annotations; 4 | using Microsoft; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using NatTypeTester.Models; 7 | using ReactiveUI; 8 | using Socks5.Models; 9 | using STUN; 10 | using STUN.Client; 11 | using STUN.Proxy; 12 | using STUN.StunResult; 13 | using System.Net; 14 | using System.Net.Sockets; 15 | using System.Reactive; 16 | using System.Reactive.Linq; 17 | 18 | namespace NatTypeTester.ViewModels; 19 | 20 | [UsedImplicitly] 21 | public class RFC3489ViewModel : ViewModelBase, IRoutableViewModel 22 | { 23 | public string UrlPathSegment => @"RFC3489"; 24 | 25 | public IScreen HostScreen => TransientCachedServiceProvider.GetRequiredService(); 26 | 27 | private Config Config => TransientCachedServiceProvider.GetRequiredService(); 28 | 29 | private IDnsClient DnsClient => TransientCachedServiceProvider.GetRequiredService(); 30 | 31 | private IDnsClient AAAADnsClient => TransientCachedServiceProvider.GetRequiredService(); 32 | 33 | private IDnsClient ADnsClient => TransientCachedServiceProvider.GetRequiredService(); 34 | 35 | private ClassicStunResult _result3489; 36 | 37 | public ClassicStunResult Result3489 38 | { 39 | get => _result3489; 40 | set => this.RaiseAndSetIfChanged(ref _result3489, value); 41 | } 42 | 43 | public ReactiveCommand TestClassicNatType { get; } 44 | 45 | public RFC3489ViewModel() 46 | { 47 | _result3489 = new ClassicStunResult(); 48 | TestClassicNatType = ReactiveCommand.CreateFromTask(TestClassicNatTypeAsync); 49 | } 50 | 51 | private async Task TestClassicNatTypeAsync(CancellationToken token) 52 | { 53 | Verify.Operation(StunServer.TryParse(Config.StunServer, out StunServer? server), @"Wrong STUN Server!"); 54 | 55 | if (!HostnameEndpoint.TryParse(Config.ProxyServer, out HostnameEndpoint? proxyIpe)) 56 | { 57 | throw new NotSupportedException(@"Unknown proxy address"); 58 | } 59 | 60 | Socks5CreateOption socks5Option = new() 61 | { 62 | Address = await DnsClient.QueryAsync(proxyIpe.Hostname, token), 63 | Port = proxyIpe.Port, 64 | UsernamePassword = new UsernamePassword 65 | { 66 | UserName = Config.ProxyUser, 67 | Password = Config.ProxyPassword 68 | } 69 | }; 70 | 71 | IPAddress? serverIp; 72 | 73 | if (Result3489.LocalEndPoint is null) 74 | { 75 | serverIp = await DnsClient.QueryAsync(server.Hostname, token); 76 | Result3489.LocalEndPoint = serverIp.AddressFamily is AddressFamily.InterNetworkV6 ? new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort) : new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort); 77 | } 78 | else 79 | { 80 | if (Result3489.LocalEndPoint.AddressFamily is AddressFamily.InterNetworkV6) 81 | { 82 | serverIp = await AAAADnsClient.QueryAsync(server.Hostname, token); 83 | } 84 | else 85 | { 86 | serverIp = await ADnsClient.QueryAsync(server.Hostname, token); 87 | } 88 | } 89 | 90 | using IUdpProxy proxy = ProxyFactory.CreateProxy(Config.ProxyType, Result3489.LocalEndPoint, socks5Option); 91 | 92 | using StunClient3489 client = new(new IPEndPoint(serverIp, server.Port), Result3489.LocalEndPoint, proxy); 93 | 94 | try 95 | { 96 | using (Observable.Interval(TimeSpan.FromSeconds(0.1)) 97 | .ObserveOn(RxApp.MainThreadScheduler) 98 | // ReSharper disable once AccessToDisposedClosure 99 | .Subscribe(_ => Result3489 = client.State with { })) 100 | { 101 | await client.ConnectProxyAsync(token); 102 | 103 | try 104 | { 105 | await client.QueryAsync(token); 106 | } 107 | finally 108 | { 109 | await client.CloseProxyAsync(token); 110 | } 111 | } 112 | } 113 | finally 114 | { 115 | Result3489 = client.State with { }; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/RFC5780ViewModel.cs: -------------------------------------------------------------------------------- 1 | using Dns.Net.Abstractions; 2 | using Dns.Net.Clients; 3 | using JetBrains.Annotations; 4 | using Microsoft; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using NatTypeTester.Models; 7 | using ReactiveUI; 8 | using Socks5.Models; 9 | using STUN; 10 | using STUN.Client; 11 | using STUN.Enums; 12 | using STUN.Proxy; 13 | using STUN.StunResult; 14 | using System.Net; 15 | using System.Net.Sockets; 16 | using System.Reactive; 17 | using System.Reactive.Linq; 18 | 19 | namespace NatTypeTester.ViewModels; 20 | 21 | [UsedImplicitly] 22 | public class RFC5780ViewModel : ViewModelBase, IRoutableViewModel 23 | { 24 | public string UrlPathSegment => @"RFC5780"; 25 | 26 | public IScreen HostScreen => TransientCachedServiceProvider.GetRequiredService(); 27 | 28 | private Config Config => TransientCachedServiceProvider.GetRequiredService(); 29 | 30 | private IDnsClient DnsClient => TransientCachedServiceProvider.GetRequiredService(); 31 | 32 | private IDnsClient AAAADnsClient => TransientCachedServiceProvider.GetRequiredService(); 33 | 34 | private IDnsClient ADnsClient => TransientCachedServiceProvider.GetRequiredService(); 35 | 36 | private StunResult5389 _result5389; 37 | 38 | public StunResult5389 Result5389 39 | { 40 | get => _result5389; 41 | set => this.RaiseAndSetIfChanged(ref _result5389, value); 42 | } 43 | 44 | private StunResult5389 _udpResult; 45 | private StunResult5389 _tcpResult; 46 | private StunResult5389 _tlsResult; 47 | 48 | private TransportType _transportType; 49 | 50 | public TransportType TransportType 51 | { 52 | get => _transportType; 53 | set => this.RaiseAndSetIfChanged(ref _transportType, value); 54 | } 55 | 56 | public ReactiveCommand DiscoveryNatType { get; } 57 | 58 | public RFC5780ViewModel() 59 | { 60 | _udpResult = new StunResult5389(); 61 | _tcpResult = new StunResult5389(); 62 | _tlsResult = new StunResult5389(); 63 | _result5389 = _udpResult; 64 | DiscoveryNatType = ReactiveCommand.CreateFromTask(DiscoveryNatTypeAsync); 65 | } 66 | 67 | private async Task DiscoveryNatTypeAsync(CancellationToken token) 68 | { 69 | Verify.Operation(StunServer.TryParse(Config.StunServer, out StunServer? server, TransportType is TransportType.Tls ? StunServer.DefaultTlsPort : StunServer.DefaultPort), @"Wrong STUN Server!"); 70 | 71 | if (!HostnameEndpoint.TryParse(Config.ProxyServer, out HostnameEndpoint? proxyIpe)) 72 | { 73 | throw new NotSupportedException(@"Unknown proxy address"); 74 | } 75 | 76 | Socks5CreateOption socks5Option = new() 77 | { 78 | Address = await DnsClient.QueryAsync(proxyIpe.Hostname, token), 79 | Port = proxyIpe.Port, 80 | UsernamePassword = new UsernamePassword 81 | { 82 | UserName = Config.ProxyUser, 83 | Password = Config.ProxyPassword 84 | } 85 | }; 86 | 87 | IPAddress? serverIp; 88 | 89 | if (Result5389.LocalEndPoint is null) 90 | { 91 | serverIp = await DnsClient.QueryAsync(server.Hostname, token); 92 | Result5389.LocalEndPoint = serverIp.AddressFamily is AddressFamily.InterNetworkV6 ? new IPEndPoint(IPAddress.IPv6Any, IPEndPoint.MinPort) : new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort); 93 | } 94 | else 95 | { 96 | if (Result5389.LocalEndPoint.AddressFamily is AddressFamily.InterNetworkV6) 97 | { 98 | serverIp = await AAAADnsClient.QueryAsync(server.Hostname, token); 99 | } 100 | else 101 | { 102 | serverIp = await ADnsClient.QueryAsync(server.Hostname, token); 103 | } 104 | } 105 | 106 | TransportType transport = TransportType; 107 | 108 | if (transport is TransportType.Udp) 109 | { 110 | using IUdpProxy proxy = ProxyFactory.CreateProxy(Config.ProxyType, Result5389.LocalEndPoint, socks5Option); 111 | using StunClient5389UDP client = new(new IPEndPoint(serverIp, server.Port), Result5389.LocalEndPoint, proxy); 112 | 113 | try 114 | { 115 | using (Observable.Interval(TimeSpan.FromSeconds(0.1)) 116 | .ObserveOn(RxApp.MainThreadScheduler) 117 | // ReSharper disable once AccessToDisposedClosure 118 | .Subscribe(_ => Result5389 = _udpResult = client.State with { })) 119 | { 120 | await client.ConnectProxyAsync(token); 121 | 122 | try 123 | { 124 | await client.QueryAsync(token); 125 | } 126 | finally 127 | { 128 | await client.CloseProxyAsync(token); 129 | } 130 | } 131 | } 132 | finally 133 | { 134 | Result5389 = _udpResult = client.State with { }; 135 | } 136 | } 137 | else 138 | { 139 | using ITcpProxy proxy = ProxyFactory.CreateProxy(transport, Config.ProxyType, socks5Option, server.Hostname); 140 | using IStunClient5389 client = new StunClient5389TCP(new IPEndPoint(serverIp, server.Port), Result5389.LocalEndPoint, proxy); 141 | 142 | try 143 | { 144 | using (Observable.Interval(TimeSpan.FromSeconds(0.1)) 145 | .ObserveOn(RxApp.MainThreadScheduler) 146 | .Subscribe(_ => UpdateData())) 147 | { 148 | await client.QueryAsync(token); 149 | } 150 | } 151 | finally 152 | { 153 | UpdateData(); 154 | } 155 | 156 | void UpdateData() 157 | { 158 | // ReSharper disable once AccessToDisposedClosure 159 | Result5389 = client.State with { }; 160 | 161 | if (transport is TransportType.Tcp) 162 | { 163 | _tcpResult = Result5389; 164 | } 165 | else 166 | { 167 | _tlsResult = Result5389; 168 | } 169 | } 170 | } 171 | } 172 | 173 | public void ResetResult() 174 | { 175 | Result5389 = TransportType switch 176 | { 177 | TransportType.Tcp => _tcpResult, 178 | TransportType.Tls => _tlsResult, 179 | _ => _udpResult 180 | }; 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/SettingViewModel.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using NatTypeTester.Models; 4 | using ReactiveUI; 5 | 6 | namespace NatTypeTester.ViewModels; 7 | 8 | [UsedImplicitly] 9 | public class SettingViewModel : ViewModelBase, IRoutableViewModel 10 | { 11 | public string UrlPathSegment => @"Settings"; 12 | 13 | public IScreen HostScreen => TransientCachedServiceProvider.GetRequiredService(); 14 | 15 | public Config Config => TransientCachedServiceProvider.GetRequiredService(); 16 | } 17 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/ValueConverters/StringToIPEndpointTypeConverter.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using ReactiveUI; 3 | using System.Net; 4 | using Volo.Abp.DependencyInjection; 5 | 6 | namespace NatTypeTester.ViewModels.ValueConverters; 7 | 8 | [ExposeServices(typeof(IBindingTypeConverter))] 9 | [UsedImplicitly] 10 | public class StringToIPEndpointTypeConverter : IBindingTypeConverter, ISingletonDependency 11 | { 12 | public int GetAffinityForObjects(Type fromType, Type toType) 13 | { 14 | if (fromType == typeof(string) && toType == typeof(IPEndPoint)) 15 | { 16 | return 11; 17 | } 18 | 19 | if (fromType == typeof(IPEndPoint) && toType == typeof(string)) 20 | { 21 | return 11; 22 | } 23 | 24 | return 0; 25 | } 26 | 27 | public bool TryConvert(object? from, Type toType, object? conversionHint, out object? result) 28 | { 29 | if (toType == typeof(IPEndPoint) && from is string str) 30 | { 31 | if (IPEndPoint.TryParse(str, out IPEndPoint? ipe)) 32 | { 33 | result = ipe; 34 | return true; 35 | } 36 | 37 | result = null; 38 | return true; 39 | } 40 | 41 | if (from is IPEndPoint fromIPEndPoint) 42 | { 43 | result = fromIPEndPoint.ToString(); 44 | } 45 | else 46 | { 47 | result = string.Empty; 48 | } 49 | 50 | return true; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/NatTypeTester.ViewModels/ViewModelBase.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using ReactiveUI; 3 | using Volo.Abp.DependencyInjection; 4 | 5 | namespace NatTypeTester.ViewModels; 6 | 7 | public abstract class ViewModelBase : ReactiveObject, ISingletonDependency 8 | { 9 | public required ITransientCachedServiceProvider TransientCachedServiceProvider { get; init; } 10 | 11 | protected IServiceProvider ServiceProvider => TransientCachedServiceProvider.GetRequiredService(); 12 | } 13 | -------------------------------------------------------------------------------- /src/NatTypeTester/App.xaml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/NatTypeTester/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Splat.Microsoft.Extensions.DependencyInjection; 3 | using System.Windows; 4 | using Volo.Abp; 5 | 6 | #pragma warning disable VSTHRD100 // 避免使用 Async Void 方法 7 | namespace NatTypeTester; 8 | 9 | public partial class App 10 | { 11 | private readonly IAbpApplicationWithInternalServiceProvider _application; 12 | 13 | public App() 14 | { 15 | _application = AbpApplicationFactory.Create(options => 16 | { 17 | options.UseAutofac(); 18 | }); 19 | } 20 | 21 | protected override async void OnStartup(StartupEventArgs e) 22 | { 23 | try 24 | { 25 | await _application.InitializeAsync(); 26 | _application.ServiceProvider.UseMicrosoftDependencyResolver(); 27 | _application.Services.GetRequiredService().Show(); 28 | } 29 | catch (Exception ex) 30 | { 31 | MessageBox.Show(ex.Message, nameof(NatTypeTester), MessageBoxButton.OK, MessageBoxImage.Error); 32 | } 33 | } 34 | 35 | protected override async void OnExit(ExitEventArgs e) 36 | { 37 | await _application.ShutdownAsync(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/NatTypeTester/Dialogs/DisposableContentDialog.cs: -------------------------------------------------------------------------------- 1 | using ModernWpf.Controls; 2 | 3 | namespace NatTypeTester.Dialogs; 4 | 5 | public class DisposableContentDialog : ContentDialog, IDisposable 6 | { 7 | public void Dispose() 8 | { 9 | Hide(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/NatTypeTester/MainWindow.xaml: -------------------------------------------------------------------------------- 1 | 14 | 15 | 16 | 17 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 36 | 37 | 38 | 39 | 40 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/NatTypeTester/MainWindow.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using ModernWpf.Controls; 3 | using NatTypeTester.ViewModels; 4 | using ReactiveMarbles.ObservableEvents; 5 | using ReactiveUI; 6 | using System.Reactive.Disposables; 7 | using Volo.Abp.DependencyInjection; 8 | 9 | namespace NatTypeTester; 10 | 11 | public partial class MainWindow : ISingletonDependency 12 | { 13 | public MainWindow(MainWindowViewModel viewModel, IServiceProvider serviceProvider) 14 | { 15 | InitializeComponent(); 16 | ViewModel = viewModel; 17 | 18 | this.WhenActivated(d => 19 | { 20 | #region Server 21 | 22 | this.Bind(ViewModel, 23 | vm => vm.Config.StunServer, 24 | v => v.ServersComboBox.Text 25 | ).DisposeWith(d); 26 | 27 | this.OneWayBind(ViewModel, 28 | vm => vm.StunServers, 29 | v => v.ServersComboBox.ItemsSource 30 | ).DisposeWith(d); 31 | 32 | #endregion 33 | 34 | this.OneWayBind(ViewModel, vm => vm.Router, v => v.RoutedViewHost.Router).DisposeWith(d); 35 | 36 | NavigationView.Events().SelectionChanged 37 | .Subscribe(parameter => 38 | { 39 | if (parameter.args.IsSettingsSelected) 40 | { 41 | ViewModel.Router.Navigate.Execute(serviceProvider.GetRequiredService()).Subscribe().Dispose(); 42 | return; 43 | } 44 | 45 | if (parameter.args.SelectedItem is not NavigationViewItem { Tag: string tag }) 46 | { 47 | return; 48 | } 49 | 50 | switch (tag) 51 | { 52 | case @"1": 53 | { 54 | ViewModel.Router.Navigate.Execute(serviceProvider.GetRequiredService()).Subscribe().Dispose(); 55 | break; 56 | } 57 | case @"2": 58 | { 59 | ViewModel.Router.Navigate.Execute(serviceProvider.GetRequiredService()).Subscribe().Dispose(); 60 | break; 61 | } 62 | } 63 | }).DisposeWith(d); 64 | NavigationView.SelectedItem = NavigationView.MenuItems.OfType().First(); 65 | 66 | ViewModel.LoadStunServer(); 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/NatTypeTester/NatTypeTester.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0-windows10.0.22621.0 5 | WinExe 6 | true 7 | 8.0.3 8 | icon.ico 9 | app.manifest 10 | true 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | True 33 | Designer 34 | MSBuild:Compile 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /src/NatTypeTester/NatTypeTesterModule.cs: -------------------------------------------------------------------------------- 1 | using JetBrains.Annotations; 2 | using Microsoft.Extensions.DependencyInjection.Extensions; 3 | using NatTypeTester.ViewModels; 4 | using ReactiveUI; 5 | using Splat; 6 | using Splat.Microsoft.Extensions.DependencyInjection; 7 | using Volo.Abp.Autofac; 8 | using Volo.Abp.Modularity; 9 | 10 | namespace NatTypeTester; 11 | 12 | [DependsOn( 13 | typeof(AbpAutofacModule), 14 | typeof(NatTypeTesterViewModelModule) 15 | )] 16 | [UsedImplicitly] 17 | public class NatTypeTesterModule : AbpModule 18 | { 19 | public override void PreConfigureServices(ServiceConfigurationContext context) 20 | { 21 | context.Services.UseMicrosoftDependencyResolver(); 22 | Locator.CurrentMutable.InitializeSplat(); 23 | Locator.CurrentMutable.InitializeReactiveUI(RegistrationNamespace.Wpf); 24 | } 25 | 26 | public override void ConfigureServices(ServiceConfigurationContext context) 27 | { 28 | context.Services.TryAddTransient(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/NatTypeTester/Properties/DesignTimeResources.xaml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/NatTypeTester/Utils/Extensions.cs: -------------------------------------------------------------------------------- 1 | using NatTypeTester.Dialogs; 2 | 3 | namespace NatTypeTester.Utils; 4 | 5 | public static class Extensions 6 | { 7 | public static async Task HandleExceptionWithContentDialogAsync(this Exception ex) 8 | { 9 | using DisposableContentDialog dialog = new(); 10 | dialog.Title = nameof(NatTypeTester); 11 | dialog.Content = ex.Message; 12 | dialog.PrimaryButtonText = @"OK"; 13 | await dialog.ShowAsync(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/NatTypeTester/Views/RFC3489View.xaml: -------------------------------------------------------------------------------- 1 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 25 | 30 | 0.0.0.0:0 31 | [::]:0 32 | 33 | 37 | 38 |