├── .editorconfig ├── .github ├── dependabot.yml └── workflows │ ├── codeql-analysis.yml │ ├── test.yml │ └── zizmor.yml ├── .gitignore ├── .gitmodules ├── Dockerfile ├── LICENSE ├── MaxMind-logo.png ├── MaxMind.GeoIP2.Benchmark ├── GlobalSuppressions.cs ├── MaxMind.GeoIP2.Benchmark.csproj ├── Program.cs └── Properties │ └── AssemblyInfo.cs ├── MaxMind.GeoIP2.UnitTests ├── DatabaseReaderTests.cs ├── DeserializationTests.cs ├── GlobalSuppressions.cs ├── MaxMind.GeoIP2.UnitTests.csproj ├── Model │ └── LocationTests.cs ├── NamedEntityTests.cs ├── Properties │ └── AssemblyInfo.cs ├── ResponseHelper.cs ├── ResponseTests.cs ├── TestUtils.cs └── WebServiceClientTests.cs ├── MaxMind.GeoIP2.sln ├── MaxMind.GeoIP2.sln.DotSettings ├── MaxMind.GeoIP2 ├── CompatibilitySuppressions.xml ├── CustomDictionary.xml ├── DatabaseReader.cs ├── Exceptions │ ├── AddressNotFoundException.cs │ ├── AuthenticationException.cs │ ├── GeoIP2Exception.cs │ ├── HttpException.cs │ ├── InvalidRequestException.cs │ ├── OutOfQueriesException.cs │ └── PermissionRequiredException.cs ├── GlobalSuppressions.cs ├── Http │ ├── Client.cs │ ├── ISyncClient.cs │ ├── Response.cs │ └── SyncClient.cs ├── IGeoIP2DatabaseReader.cs ├── IGeoIP2Provider.cs ├── IGeoIP2WebServicesClient.cs ├── MaxMind.GeoIP2.csproj ├── MaxMind.GeoIP2.nuspec ├── MaxMind.GeoIP2.ruleset ├── Model │ ├── City.cs │ ├── Continent.cs │ ├── Country.cs │ ├── Location.cs │ ├── MaxMind.cs │ ├── NamedEntity.cs │ ├── Postal.cs │ ├── RepresentedCountry.cs │ ├── Subdivision.cs │ ├── Traits.cs │ └── WebServiceError.cs ├── NetworkConverter.cs ├── NuGet.targets ├── Properties │ └── AssemblyInfo.cs ├── Responses │ ├── AbstractCityResponse.cs │ ├── AbstractCountryResponse.cs │ ├── AbstractResponse.cs │ ├── AnonymousIPResponse.cs │ ├── AnonymousPlusResponse.cs │ ├── AsnResponse.cs │ ├── CityResponse.cs │ ├── ConnectionTypeResponse.cs │ ├── CountryResponse.cs │ ├── DomainResponse.cs │ ├── EnterpriseResponse.cs │ ├── InsightsResponse.cs │ └── IspResponse.cs ├── WebServiceClient.cs └── WebServiceClientOptions.cs ├── MaxMind.snk ├── README.dev.md ├── README.md ├── dev-bin └── release.ps1 └── releasenotes.md /.editorconfig: -------------------------------------------------------------------------------- 1 | # Remove the line below if you want to inherit .editorconfig settings from higher directories 2 | root = true 3 | 4 | # C# files 5 | [*.cs] 6 | 7 | #### Core EditorConfig Options #### 8 | 9 | # Indentation and spacing 10 | indent_size = 4 11 | indent_style = space 12 | tab_width = 4 13 | 14 | # New line preferences 15 | end_of_line = crlf 16 | insert_final_newline = false 17 | 18 | #### .NET Coding Conventions #### 19 | 20 | # Organize usings 21 | dotnet_separate_import_directive_groups = false 22 | dotnet_sort_system_directives_first = false 23 | file_header_template = unset 24 | 25 | # this. and Me. preferences 26 | dotnet_style_qualification_for_event = false 27 | dotnet_style_qualification_for_field = false 28 | dotnet_style_qualification_for_method = false 29 | dotnet_style_qualification_for_property = false 30 | 31 | # Language keywords vs BCL types preferences 32 | dotnet_style_predefined_type_for_locals_parameters_members = true 33 | dotnet_style_predefined_type_for_member_access = true 34 | 35 | # Parentheses preferences 36 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity 37 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity 38 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary 39 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity 40 | 41 | # Modifier preferences 42 | dotnet_style_require_accessibility_modifiers = for_non_interface_members 43 | 44 | # Expression-level preferences 45 | dotnet_style_coalesce_expression = true 46 | dotnet_style_collection_initializer = true 47 | dotnet_style_explicit_tuple_names = true 48 | dotnet_style_namespace_match_folder = true 49 | dotnet_style_null_propagation = true 50 | dotnet_style_object_initializer = true 51 | dotnet_style_operator_placement_when_wrapping = beginning_of_line 52 | dotnet_style_prefer_auto_properties = true 53 | dotnet_style_prefer_compound_assignment = true 54 | dotnet_style_prefer_conditional_expression_over_assignment = true 55 | dotnet_style_prefer_conditional_expression_over_return = true 56 | dotnet_style_prefer_inferred_anonymous_type_member_names = true 57 | dotnet_style_prefer_inferred_tuple_names = true 58 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true 59 | dotnet_style_prefer_simplified_boolean_expressions = true 60 | dotnet_style_prefer_simplified_interpolation = true 61 | 62 | # Field preferences 63 | dotnet_style_readonly_field = true 64 | 65 | # Parameter preferences 66 | dotnet_code_quality_unused_parameters = all 67 | 68 | # Suppression preferences 69 | dotnet_remove_unnecessary_suppression_exclusions = none 70 | 71 | # New line preferences 72 | dotnet_style_allow_multiple_blank_lines_experimental = true 73 | dotnet_style_allow_statement_immediately_after_block_experimental = true 74 | 75 | #### C# Coding Conventions #### 76 | 77 | # var preferences 78 | csharp_style_var_elsewhere = true 79 | csharp_style_var_for_built_in_types = true 80 | csharp_style_var_when_type_is_apparent = true 81 | 82 | # Expression-bodied members 83 | csharp_style_expression_bodied_accessors = true 84 | csharp_style_expression_bodied_constructors = false 85 | csharp_style_expression_bodied_indexers = true 86 | csharp_style_expression_bodied_lambdas = true 87 | csharp_style_expression_bodied_local_functions = false 88 | csharp_style_expression_bodied_methods = false 89 | csharp_style_expression_bodied_operators = false 90 | csharp_style_expression_bodied_properties = true 91 | 92 | # Pattern matching preferences 93 | csharp_style_pattern_matching_over_as_with_null_check = true 94 | csharp_style_pattern_matching_over_is_with_cast_check = true 95 | csharp_style_prefer_not_pattern = true 96 | csharp_style_prefer_pattern_matching = true 97 | csharp_style_prefer_switch_expression = true 98 | 99 | # Null-checking preferences 100 | csharp_style_conditional_delegate_call = true 101 | 102 | # Modifier preferences 103 | csharp_prefer_static_local_function = true 104 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async 105 | 106 | # Code-block preferences 107 | csharp_prefer_braces = true 108 | csharp_prefer_simple_using_statement = true 109 | csharp_style_namespace_declarations = block_scoped 110 | 111 | # Expression-level preferences 112 | csharp_prefer_simple_default_expression = true 113 | csharp_style_deconstructed_variable_declaration = true 114 | csharp_style_implicit_object_creation_when_type_is_apparent = true 115 | csharp_style_inlined_variable_declaration = true 116 | csharp_style_pattern_local_over_anonymous_function = true 117 | csharp_style_prefer_index_operator = true 118 | csharp_style_prefer_null_check_over_type_check = true 119 | csharp_style_prefer_range_operator = true 120 | csharp_style_throw_expression = true 121 | csharp_style_unused_value_assignment_preference = discard_variable 122 | csharp_style_unused_value_expression_statement_preference = discard_variable 123 | 124 | # 'using' directive preferences 125 | csharp_using_directive_placement = outside_namespace 126 | 127 | # New line preferences 128 | csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true 129 | csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true 130 | csharp_style_allow_embedded_statements_on_same_line_experimental = true 131 | 132 | #### C# Formatting Rules #### 133 | 134 | # New line preferences 135 | csharp_new_line_before_catch = true 136 | csharp_new_line_before_else = true 137 | csharp_new_line_before_finally = true 138 | csharp_new_line_before_members_in_anonymous_types = true 139 | csharp_new_line_before_members_in_object_initializers = true 140 | csharp_new_line_before_open_brace = all 141 | csharp_new_line_between_query_expression_clauses = true 142 | 143 | # Indentation preferences 144 | csharp_indent_block_contents = true 145 | csharp_indent_braces = false 146 | csharp_indent_case_contents = true 147 | csharp_indent_case_contents_when_block = true 148 | csharp_indent_labels = no_change 149 | csharp_indent_switch_labels = true 150 | 151 | # Space preferences 152 | csharp_space_after_cast = false 153 | csharp_space_after_colon_in_inheritance_clause = true 154 | csharp_space_after_comma = true 155 | csharp_space_after_dot = false 156 | csharp_space_after_keywords_in_control_flow_statements = true 157 | csharp_space_after_semicolon_in_for_statement = true 158 | csharp_space_around_binary_operators = before_and_after 159 | csharp_space_around_declaration_statements = false 160 | csharp_space_before_colon_in_inheritance_clause = true 161 | csharp_space_before_comma = false 162 | csharp_space_before_dot = false 163 | csharp_space_before_open_square_brackets = false 164 | csharp_space_before_semicolon_in_for_statement = false 165 | csharp_space_between_empty_square_brackets = false 166 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 167 | csharp_space_between_method_call_name_and_opening_parenthesis = false 168 | csharp_space_between_method_call_parameter_list_parentheses = false 169 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 170 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 171 | csharp_space_between_method_declaration_parameter_list_parentheses = false 172 | csharp_space_between_parentheses = false 173 | csharp_space_between_square_brackets = false 174 | 175 | # Wrapping preferences 176 | csharp_preserve_single_line_blocks = true 177 | csharp_preserve_single_line_statements = true 178 | 179 | #### Naming styles #### 180 | 181 | # Naming rules 182 | 183 | dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion 184 | dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface 185 | dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i 186 | 187 | dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion 188 | dotnet_naming_rule.types_should_be_pascal_case.symbols = types 189 | dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case 190 | 191 | dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion 192 | dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members 193 | dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case 194 | 195 | # Symbol specifications 196 | 197 | dotnet_naming_symbols.interface.applicable_kinds = interface 198 | dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 199 | dotnet_naming_symbols.interface.required_modifiers = 200 | 201 | dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum 202 | dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 203 | dotnet_naming_symbols.types.required_modifiers = 204 | 205 | dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method 206 | dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 207 | dotnet_naming_symbols.non_field_members.required_modifiers = 208 | 209 | # Naming styles 210 | 211 | dotnet_naming_style.pascal_case.required_prefix = 212 | dotnet_naming_style.pascal_case.required_suffix = 213 | dotnet_naming_style.pascal_case.word_separator = 214 | dotnet_naming_style.pascal_case.capitalization = pascal_case 215 | 216 | dotnet_naming_style.begins_with_i.required_prefix = I 217 | dotnet_naming_style.begins_with_i.required_suffix = 218 | dotnet_naming_style.begins_with_i.word_separator = 219 | dotnet_naming_style.begins_with_i.capitalization = pascal_case 220 | 221 | # Options 222 | 223 | # RCS1118: Mark local variable as const. Although this sounds OK, 224 | # it tends to lead to verbose code, is "const string ip" instead 225 | # of "var ip". 226 | dotnet_diagnostic.RCS1118.severity = silent 227 | 228 | # RSC1146: Use conditional access. I find the resulting code somewhat more 229 | # confusing to read, e.g., "response.ContentType?.Contains("json") != true" 230 | dotnet_diagnostic.RCS1146.severity = silent 231 | 232 | roslynator_accessibility_modifiers = explicit 233 | # Applicable to: rcs1018 234 | 235 | roslynator_accessor_braces_style = multi_line 236 | # Default: multi_line 237 | # Applicable to: rcs0020 238 | 239 | roslynator_array_creation_type_style = implicit 240 | # Applicable to: rcs1014 241 | 242 | roslynator_arrow_token_new_line = before 243 | # Applicable to: rcs0032 244 | 245 | roslynator_binary_operator_new_line = before 246 | # Applicable to: rcs0027 247 | 248 | roslynator_blank_line_between_closing_brace_and_switch_section = true 249 | # Applicable to: rcs0014, rcs1036 250 | 251 | roslynator_blank_line_between_single_line_accessors = true 252 | # Applicable to: rcs0011 253 | 254 | roslynator_blank_line_between_using_directives = separate_groups 255 | # Applicable to: rcs0015 256 | 257 | roslynator_body_style = expression 258 | # Applicable to: rcs1016 259 | 260 | roslynator_conditional_operator_condition_parentheses_style = omit_when_condition_is_single_token 261 | # Applicable to: rcs1051 262 | 263 | roslynator_conditional_operator_new_line = before 264 | # Applicable to: rcs0028 265 | 266 | roslynator_configure_await = true 267 | # Applicable to: rcs1090 268 | 269 | roslynator_empty_string_style = literal 270 | # Applicable to: rcs1078 271 | 272 | roslynator_enum_has_flag_style = operator 273 | # Applicable to: rcs1096 274 | 275 | roslynator_equals_token_new_line = before 276 | # Applicable to: rcs0052 277 | 278 | roslynator_new_line_at_end_of_file = true 279 | # Applicable to: rcs0058 280 | 281 | roslynator_new_line_before_while_in_do_statement = false 282 | # Applicable to: rcs0051 283 | 284 | roslynator_null_conditional_operator_new_line = before 285 | # Applicable to: rcs0059 286 | 287 | roslynator_null_check_style = pattern_matching 288 | # Applicable to: rcs1248 289 | 290 | roslynator_object_creation_parentheses_style = omit 291 | # Applicable to: rcs1050 292 | 293 | roslynator_object_creation_type_style = implicit_when_type_is_obvious 294 | # Applicable to: rcs1250 295 | 296 | roslynator_prefix_field_identifier_with_underscore = true 297 | 298 | roslynator_suppress_unity_script_methods = true 299 | # Applicable to: rcs1213 300 | 301 | roslynator_use_anonymous_function_or_method_group = anonymous_function 302 | # Applicable to: rcs1207 303 | 304 | roslynator_use_block_body_when_declaration_spans_over_multiple_lines = true 305 | # Applicable to: rcs1016 306 | 307 | roslynator_use_block_body_when_expression_spans_over_multiple_lines = true 308 | # Applicable to: rcs1016 309 | 310 | roslynator_use_var_instead_of_implicit_object_creation = true 311 | # Applicable to: rcs1250 312 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: nuget 4 | directories: 5 | - "**/*" 6 | schedule: 7 | interval: daily 8 | open-pull-requests-limit: 10 9 | - package-ecosystem: "github-actions" 10 | directory: "/" 11 | schedule: 12 | interval: daily 13 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "Code scanning - action" 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - 'dependabot/**' 7 | pull_request: 8 | schedule: 9 | - cron: '0 1 * * 1' 10 | 11 | jobs: 12 | CodeQL-Build: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | permissions: 17 | security-events: write 18 | 19 | steps: 20 | - name: Checkout repository 21 | uses: actions/checkout@v4 22 | with: 23 | # We must fetch at least the immediate parents so that if this is 24 | # a pull request then we can checkout the head. 25 | fetch-depth: 2 26 | persist-credentials: false 27 | 28 | # If this run was triggered by a pull request event, then checkout 29 | # the head of the pull request instead of the merge commit. 30 | - run: git checkout HEAD^2 31 | if: ${{ github.event_name == 'pull_request' }} 32 | 33 | - name: Setup .NET 34 | uses: actions/setup-dotnet@v4 35 | with: 36 | dotnet-version: | 37 | 8.0.x 38 | 9.0.x 39 | 40 | # Initializes the CodeQL tools for scanning. 41 | - name: Initialize CodeQL 42 | uses: github/codeql-action/init@v3 43 | # Override language selection by uncommenting this and choosing your languages 44 | # with: 45 | # languages: go, javascript, csharp, python, cpp, java 46 | 47 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 48 | # If this step fails, then you should remove it and run the build manually (see below) 49 | - name: Autobuild 50 | uses: github/codeql-action/autobuild@v3 51 | 52 | # ℹ️ Command-line programs to run using the OS shell. 53 | # 📚 https://git.io/JvXDl 54 | 55 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 56 | # and modify them (or add more) to build your code if your project 57 | # uses a compiled language 58 | 59 | #- run: | 60 | # make bootstrap 61 | # make release 62 | 63 | - name: Perform CodeQL Analysis 64 | uses: github/codeql-action/analyze@v3 65 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | on: 3 | push: 4 | pull_request: 5 | schedule: 6 | - cron: '3 20 * * SUN' 7 | 8 | permissions: {} 9 | 10 | jobs: 11 | build: 12 | strategy: 13 | matrix: 14 | platform: [ubuntu-latest, macos-latest, windows-latest] 15 | runs-on: ${{ matrix.platform }} 16 | name: Dotnet on ${{ matrix.platform }} 17 | steps: 18 | - uses: actions/checkout@v4 19 | with: 20 | submodules: true 21 | persist-credentials: false 22 | 23 | - name: Setup .NET 24 | uses: actions/setup-dotnet@v4 25 | with: 26 | dotnet-version: | 27 | 8.0.x 28 | 9.0.x 29 | 30 | - name: Build 31 | run: | 32 | dotnet build MaxMind.GeoIP2 33 | dotnet build MaxMind.GeoIP2.Benchmark 34 | dotnet build MaxMind.GeoIP2.UnitTests 35 | 36 | - name: Run benchmark 37 | run: dotnet run -f net8.0 -p MaxMind.GeoIP2.Benchmark/MaxMind.GeoIP2.Benchmark.csproj 38 | env: 39 | MAXMIND_BENCHMARK_DB: ${{ github.workspace }}/MaxMind.GeoIP2.UnitTests/TestData/MaxMind-DB/test-data/GeoIP2-City-Test.mmdb 40 | 41 | - name: Run tests 42 | run: dotnet test MaxMind.GeoIP2.UnitTests/MaxMind.GeoIP2.UnitTests.csproj 43 | env: 44 | MAXMIND_TEST_BASE_DIR: ${{ github.workspace }}/MaxMind.GeoIP2.UnitTests 45 | -------------------------------------------------------------------------------- /.github/workflows/zizmor.yml: -------------------------------------------------------------------------------- 1 | name: GitHub Actions Security Analysis with zizmor 2 | 3 | on: 4 | push: 5 | branches: ["main"] 6 | pull_request: 7 | branches: ["**"] 8 | 9 | jobs: 10 | zizmor: 11 | name: zizmor latest via PyPI 12 | runs-on: ubuntu-latest 13 | permissions: 14 | security-events: write 15 | # required for workflows in private repositories 16 | contents: read 17 | actions: read 18 | steps: 19 | - name: Checkout repository 20 | uses: actions/checkout@v4 21 | with: 22 | persist-credentials: false 23 | 24 | - name: Install the latest version of uv 25 | uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # 6.1.0 26 | with: 27 | enable-cache: false 28 | 29 | - name: Run zizmor 30 | run: uvx zizmor@1.7.0 --format plain . 31 | env: 32 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 2 | [Bb]in/ 3 | [Oo]bj/ 4 | 5 | # dotnet CLI stuff 6 | .dotnetcli/ 7 | scripts/ 8 | 9 | # mstest test results 10 | TestResults 11 | 12 | # vscode folder 13 | .vscode/ 14 | ## Ignore Visual Studio temporary files, build results, and 15 | ## files generated by popular Visual Studio add-ons. 16 | 17 | # Visual Studo 2015 cache/options directory 18 | .vs/ 19 | 20 | # User-specific files 21 | *.suo 22 | *.user 23 | *.sln.docstates 24 | 25 | # Build results 26 | [Dd]ebug/ 27 | [Rr]elease/ 28 | x64/ 29 | *_i.c 30 | *_p.c 31 | *.ilk 32 | *.meta 33 | *.nupkg 34 | *.obj 35 | *.pch 36 | *.pdb 37 | *.pgc 38 | *.pgd 39 | *.rsp 40 | *.sbr 41 | *.tlb 42 | *.tli 43 | *.tlh 44 | *.tmp 45 | *.log 46 | *.vspscc 47 | *.vssscc 48 | .builds 49 | 50 | # Visual C++ cache files 51 | ipch/ 52 | *.aps 53 | *.ncb 54 | *.opensdf 55 | *.sdf 56 | 57 | # Visual Studio profiler 58 | *.psess 59 | *.vsp 60 | *.vspx 61 | 62 | # Guidance Automation Toolkit 63 | *.gpState 64 | 65 | # ReSharper is a .NET coding add-in 66 | _ReSharper* 67 | 68 | # NCrunch 69 | *.ncrunch* 70 | .*crunch*.local.xml 71 | 72 | # Installshield output folder 73 | [Ee]xpress 74 | 75 | # DocProject is a documentation generator add-in 76 | DocProject/buildhelp/ 77 | DocProject/Help/*.HxT 78 | DocProject/Help/*.HxC 79 | DocProject/Help/*.hhc 80 | DocProject/Help/*.hhk 81 | DocProject/Help/*.hhp 82 | DocProject/Help/Html2 83 | DocProject/Help/html 84 | 85 | # Click-Once directory 86 | publish 87 | 88 | # Publish Web Output 89 | *.Publish.xml 90 | 91 | # NuGet Packages Directory 92 | packages 93 | *.lock.json 94 | 95 | # Windows Azure Build Output 96 | csx 97 | *.build.csdef 98 | 99 | # Windows Store app package directory 100 | AppPackages/ 101 | 102 | # Idea 103 | .idea 104 | *.iml 105 | 106 | # Others 107 | [Bb]in 108 | [Oo]bj 109 | artifacts 110 | sql 111 | TestResults 112 | [Tt]est[Rr]esult* 113 | *.Cache 114 | ClientBin 115 | [Ss]tyle[Cc]op.* 116 | ~$* 117 | *.dbmdl 118 | *.sw? 119 | Generated_Code #added for RIA/Silverlight projects 120 | 121 | # Backup & report files from converting an old project file to a newer 122 | # Visual Studio version. Backup files are not needed, because we have git ;-) 123 | _UpgradeReport_Files/ 124 | Backup*/ 125 | UpgradeLog*.XML 126 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "MaxMind.GeoIP2.UnitTests/TestData/MaxMind-DB"] 2 | path = MaxMind.GeoIP2.UnitTests/TestData/MaxMind-DB 3 | url = https://github.com/maxmind/MaxMind-DB.git 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM microsoft/dotnet:2.1-sdk 2 | 3 | ENV PATH="${PATH}:~/.dotnet/tools" 4 | 5 | RUN dotnet tool install --global dotnet-outdated 6 | 7 | WORKDIR /project 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | https://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /MaxMind-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxmind/GeoIP2-dotnet/42725a64c8eead3ca040a3e5a6feb80455f99eaa/MaxMind-logo.png -------------------------------------------------------------------------------- /MaxMind.GeoIP2.Benchmark/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("Major Code Smell", "S112:General exceptions should never be thrown", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Benchmark.Program.Main(System.String[])")] 9 | [assembly: SuppressMessage("Major Code Smell", "S108:Nested blocks of code should not be left empty", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Benchmark.Program.Bench(System.String,MaxMind.GeoIP2.DatabaseReader)")] 10 | [assembly: SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Benchmark.Program.Bench(System.String,MaxMind.GeoIP2.DatabaseReader)")] 11 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.Benchmark/MaxMind.GeoIP2.Benchmark.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Benchmark project to validate MaxMind GeoIP2 Database Reader and Web Service Client 5 | 5.0.0 6 | net9.0;net8.0;net481 7 | net9.0;net8.0 8 | MaxMind.GeoIP2.Benchmark 9 | Exe 10 | ../MaxMind.snk 11 | true 12 | true 13 | MaxMind.GeoIP2.Benchmark 14 | Apache-2.0 15 | false 16 | false 17 | false 18 | false 19 | false 20 | false 21 | false 22 | false 23 | 13.0 24 | enable 25 | latest 26 | true 27 | true 28 | true 29 | 30 | 31 | 32 | 9999 33 | 34 | 35 | 36 | 9999 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.Benchmark/Program.cs: -------------------------------------------------------------------------------- 1 | using MaxMind.Db; 2 | using MaxMind.GeoIP2.Exceptions; 3 | using System; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Net; 7 | 8 | namespace MaxMind.GeoIP2.Benchmark 9 | { 10 | public static class Program 11 | { 12 | private const int Count = 200000; 13 | 14 | public static void Main(string[] args) 15 | { 16 | // first we check if the command-line argument is provided 17 | var dbPath = args.Length > 0 ? args[0] : null; 18 | if (dbPath != null) 19 | { 20 | if (!File.Exists(dbPath)) 21 | { 22 | throw new Exception("Path provided by command-line argument does not exist!"); 23 | } 24 | } 25 | else 26 | { 27 | // check if environment variable MAXMIND_BENCHMARK_DB is set 28 | dbPath = Environment.GetEnvironmentVariable("MAXMIND_BENCHMARK_DB"); 29 | 30 | if (!string.IsNullOrEmpty(dbPath)) 31 | { 32 | if (!File.Exists(dbPath)) 33 | { 34 | throw new Exception("Path set as environment variable MAXMIND_BENCHMARK_DB does not exist!"); 35 | } 36 | } 37 | else 38 | { 39 | // check if GeoLite2-City.mmdb exists in CWD 40 | dbPath = "GeoLite2-City.mmdb"; 41 | 42 | if (!File.Exists(dbPath)) 43 | { 44 | throw new Exception($"{dbPath} does not exist in current directory!"); 45 | } 46 | } 47 | } 48 | 49 | using (var reader = new DatabaseReader(dbPath, FileAccessMode.Memory)) 50 | { 51 | Bench("Warm-up for Memory mode", reader); 52 | Bench("Memory mode", reader); 53 | } 54 | 55 | using (var reader = new DatabaseReader(dbPath, FileAccessMode.MemoryMapped)) 56 | { 57 | Bench("Warm-up for MMAP mode", reader); 58 | Bench("MMAP mode", reader); 59 | } 60 | } 61 | 62 | private static void Bench(string name, DatabaseReader reader) 63 | { 64 | Console.Write($"\n{name}: "); 65 | var rand = new Random(1); 66 | var s = Stopwatch.StartNew(); 67 | for (var i = 0; i < Count; i++) 68 | { 69 | var ip = new IPAddress(rand.Next(int.MaxValue)); 70 | try 71 | { 72 | reader.City(ip); 73 | } 74 | catch (AddressNotFoundException) { } 75 | } 76 | s.Stop(); 77 | Console.WriteLine("{0:N0} queries per second", Count / s.Elapsed.TotalSeconds); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.Benchmark/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("MaxMind.GeoIP2.Benchmark")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("MaxMind.GeoIP2.Benchmark")] 12 | [assembly: AssemblyCopyright("Copyright © 2013-2025")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("423dd8cd-da73-483d-ba2c-f521fd3f01eb")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("4.0.0.0")] 35 | [assembly: AssemblyFileVersion("4.0.0.0")] 36 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/DeserializationTests.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Responses; 4 | using System.Text; 5 | using System.Text.Json; 6 | using Xunit; 7 | using static MaxMind.GeoIP2.UnitTests.ResponseHelper; 8 | 9 | #endregion 10 | 11 | namespace MaxMind.GeoIP2.UnitTests 12 | { 13 | public class DeserializationTests 14 | { 15 | private static void CanDeserializeCountryResponse(CountryResponse resp) 16 | { 17 | Assert.Equal("NA", resp.Continent.Code); 18 | Assert.Equal(42, resp.Continent.GeoNameId); 19 | Assert.Equal("North America", resp.Continent.Name); 20 | 21 | Assert.Equal(1, resp.Country.GeoNameId); 22 | Assert.False(resp.Country.IsInEuropeanUnion); 23 | Assert.Equal("US", resp.Country.IsoCode); 24 | Assert.Equal(56, resp.Country.Confidence); 25 | Assert.Equal("United States", resp.Country.Name); 26 | 27 | Assert.Equal(2, resp.RegisteredCountry.GeoNameId); 28 | Assert.True(resp.RegisteredCountry.IsInEuropeanUnion); 29 | Assert.Equal("DE", resp.RegisteredCountry.IsoCode); 30 | Assert.Equal("Germany", resp.RegisteredCountry.Name); 31 | 32 | Assert.Equal(4, resp.RepresentedCountry.GeoNameId); 33 | Assert.True(resp.RepresentedCountry.IsInEuropeanUnion); 34 | Assert.Equal("GB", resp.RepresentedCountry.IsoCode); 35 | Assert.Equal("United Kingdom", resp.RepresentedCountry.Name); 36 | Assert.Equal("military", resp.RepresentedCountry.Type); 37 | 38 | Assert.True(resp.Traits.IsAnycast); 39 | Assert.Equal("1.2.3.4", resp.Traits.IPAddress); 40 | } 41 | 42 | private static void CanDeserializeInsightsResponse(InsightsResponse insights) 43 | { 44 | Assert.Equal(76, insights.City.Confidence); 45 | Assert.Equal(9876, insights.City.GeoNameId); 46 | Assert.Equal("Minneapolis", insights.City.Name); 47 | 48 | Assert.Equal("NA", insights.Continent.Code); 49 | Assert.Equal(42, insights.Continent.GeoNameId); 50 | Assert.Equal("North America", insights.Continent.Name); 51 | 52 | Assert.Equal(99, insights.Country.Confidence); 53 | Assert.Equal(1, insights.Country.GeoNameId); 54 | Assert.False(insights.Country.IsInEuropeanUnion); 55 | Assert.Equal("US", insights.Country.IsoCode); 56 | Assert.Equal("United States of America", insights.Country.Name); 57 | 58 | Assert.Equal(1500, insights.Location.AccuracyRadius); 59 | Assert.Equal(44.979999999999997, insights.Location.Latitude); 60 | Assert.Equal(93.263599999999997, insights.Location.Longitude); 61 | #pragma warning disable 0618 62 | Assert.Equal(765, insights.Location.MetroCode); 63 | #pragma warning restore 0618 64 | Assert.Equal("America/Chicago", insights.Location.TimeZone); 65 | Assert.Equal(50000, insights.Location.AverageIncome); 66 | Assert.Equal(100, insights.Location.PopulationDensity); 67 | 68 | Assert.Equal(11, insights.MaxMind.QueriesRemaining); 69 | 70 | Assert.Equal("55401", insights.Postal.Code); 71 | Assert.Equal(33, insights.Postal.Confidence); 72 | 73 | Assert.Equal(2, insights.RegisteredCountry.GeoNameId); 74 | Assert.True(insights.RegisteredCountry.IsInEuropeanUnion); 75 | Assert.Equal("DE", insights.RegisteredCountry.IsoCode); 76 | Assert.Equal("Germany", insights.RegisteredCountry.Name); 77 | 78 | Assert.Equal(3, insights.RepresentedCountry.GeoNameId); 79 | Assert.True(insights.RepresentedCountry.IsInEuropeanUnion); 80 | Assert.Equal("GB", insights.RepresentedCountry.IsoCode); 81 | Assert.Equal("United Kingdom", insights.RepresentedCountry.Name); 82 | Assert.Equal("military", insights.RepresentedCountry.Type); 83 | 84 | Assert.Equal(2, insights.Subdivisions.Count); 85 | Assert.Equal(88, insights.Subdivisions[0].Confidence); 86 | Assert.Equal(574635, insights.Subdivisions[0].GeoNameId); 87 | Assert.Equal("MN", insights.Subdivisions[0].IsoCode); 88 | Assert.Equal("Minnesota", insights.Subdivisions[0].Name); 89 | Assert.Equal("TT", insights.Subdivisions[1].IsoCode); 90 | 91 | Assert.Equal(1234, insights.Traits.AutonomousSystemNumber); 92 | Assert.Equal("AS Organization", insights.Traits.AutonomousSystemOrganization); 93 | Assert.Equal("Cable/DSL", insights.Traits.ConnectionType); 94 | Assert.Equal("example.com", insights.Traits.Domain); 95 | Assert.Equal("1.2.3.4", insights.Traits.IPAddress); 96 | Assert.True(insights.Traits.IsAnonymous); 97 | Assert.True(insights.Traits.IsAnonymousVpn); 98 | Assert.True(insights.Traits.IsHostingProvider); 99 | Assert.True(insights.Traits.IsPublicProxy); 100 | Assert.True(insights.Traits.IsResidentialProxy); 101 | Assert.True(insights.Traits.IsTorExitNode); 102 | #pragma warning disable 0618 103 | Assert.True(insights.Traits.IsAnonymousProxy); 104 | Assert.True(insights.Traits.IsSatelliteProvider); 105 | #pragma warning restore 0618 106 | Assert.True(insights.Traits.IsAnycast); 107 | Assert.Equal("Comcast", insights.Traits.Isp); 108 | Assert.Equal("310", insights.Traits.MobileCountryCode); 109 | Assert.Equal("004", insights.Traits.MobileNetworkCode); 110 | 111 | var network = insights.Traits.Network!; 112 | Assert.Equal("1.2.3.0", network.NetworkAddress.ToString()); 113 | Assert.Equal(24, network.PrefixLength); 114 | 115 | Assert.Equal("Blorg", insights.Traits.Organization); 116 | Assert.Equal(1.5, insights.Traits.StaticIPScore); 117 | Assert.Equal(1, insights.Traits.UserCount); 118 | Assert.Equal("college", insights.Traits.UserType); 119 | } 120 | 121 | [Fact] 122 | public void CanDeserializeCountryResponseNewtonsoftJson() 123 | { 124 | var options = new JsonSerializerOptions(); 125 | options.Converters.Add(new NetworkConverter()); 126 | 127 | CanDeserializeCountryResponse(JsonSerializer.Deserialize( 128 | Encoding.UTF8.GetBytes(CountryJson), options)!); 129 | } 130 | 131 | [Fact] 132 | public void CanDeserializeInsightsResponseNewtonsoftJson() 133 | { 134 | var options = new JsonSerializerOptions(); 135 | options.Converters.Add(new NetworkConverter()); 136 | 137 | CanDeserializeInsightsResponse(JsonSerializer.Deserialize( 138 | Encoding.UTF8.GetBytes(InsightsJson), options)!); 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | // This file is used by Code Analysis to maintain SuppressMessage 2 | // attributes that are applied to this project. 3 | // Project-level suppressions either have no target or are given 4 | // a specific target and scoped to a namespace, type, member, etc. 5 | 6 | using System.Diagnostics.CodeAnalysis; 7 | 8 | [assembly: SuppressMessage("Blocker Code Smell", "S2699:Tests should include assertions", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.DeserializationTests.CanDeserializeCountryResponseNewtonsoftJson")] 9 | [assembly: SuppressMessage("Blocker Code Smell", "S2699:Tests should include assertions", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.DeserializationTests.CanDeserializeInsightsResponseNewtonsoftJson")] 10 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.AddressNotFoundShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 11 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.AddressReservedShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)~System.Threading.Tasks.Task")] 12 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.AuthenticationErrorShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 13 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.BadCharsetRequirementShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)~System.Threading.Tasks.Task")] 14 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.BadContentTypeShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)~System.Threading.Tasks.Task")] 15 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.EmptyBodyShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)~System.Threading.Tasks.Task")] 16 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.IncorrectlyFormattedIPAddressShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 17 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.InsufficientFundsShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 18 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.InternalServerErrorShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)~System.Threading.Tasks.Task")] 19 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.NoErrorBodyShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 20 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.OutOfQueriesShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 21 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.PermissionRequiredShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 22 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.SurprisingStatusShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 23 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.UndeserializableJsonShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 24 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.UnexpectedErrorBodyShouldThrowExceptionAsync(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 25 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.WebServiceErrorShouldThrowException(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 26 | [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.UnitTests.WebServiceClientTests.WeirdErrorBodyShouldThrowExceptionAsync(System.String,MaxMind.GeoIP2.UnitTests.WebServiceClientTests.ClientRunner,System.Type)")] 27 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/MaxMind.GeoIP2.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Test project to validate MaxMind GeoIP2 Database Reader and Web Service Client 5 | 5.0.0 6 | net9.0;net8.0;net481 7 | net9.0;net8.0 8 | MaxMind.GeoIP2.UnitTests 9 | ../MaxMind.snk 10 | true 11 | true 12 | MaxMind.GeoIP2.UnitTests 13 | Apache-2.0 14 | true 15 | false 16 | false 17 | false 18 | false 19 | false 20 | false 21 | false 22 | false 23 | 13.0 24 | enable 25 | latest 26 | true 27 | true 28 | true 29 | 30 | 31 | 32 | 9999 33 | 34 | 35 | 36 | 9999 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | runtime; build; native; contentfiles; analyzers 45 | all 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/Model/LocationTests.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Model; 4 | using Xunit; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.UnitTests.Model 9 | { 10 | public class LocationTests 11 | { 12 | [Theory] 13 | [InlineData(null, null)] 14 | [InlineData(50.0, null)] 15 | [InlineData(null, 0.0)] 16 | public void HasCoordinatesFailure(double? latitude, double? longitude) 17 | { 18 | var location = new Location 19 | (latitude: latitude, longitude: longitude); 20 | 21 | Assert.False(location.HasCoordinates); 22 | } 23 | 24 | [Fact] 25 | public void HasCoordinatesSuccess() 26 | { 27 | var location = new Location(latitude: 50.0, longitude: 0.0); 28 | Assert.True(location.HasCoordinates); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/NamedEntityTests.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Model; 4 | using System.Collections.Generic; 5 | using Xunit; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.UnitTests 10 | { 11 | public class NamedEntityTests 12 | { 13 | [Fact] 14 | public void CanGetSingleName() 15 | { 16 | var c = new City( 17 | names: new Dictionary { { "en", "Foo" } }, 18 | locales: new List { "en" } 19 | ); 20 | 21 | Assert.Equal("Foo", c.Name); 22 | } 23 | 24 | [Fact] 25 | public void NameReturnsCorrectLocale() 26 | { 27 | var c = new City( 28 | names: new Dictionary { { "en", "Mexico City" }, { "es", "Ciudad de México" } }, 29 | locales: new List { "es" } 30 | ); 31 | 32 | Assert.Equal("Ciudad de México", c.Name); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System.Reflection; 4 | using System.Runtime.InteropServices; 5 | 6 | #endregion 7 | 8 | // General Information about an assembly is controlled through the following 9 | // set of attributes. Change these attribute values to modify the information 10 | // associated with an assembly. 11 | 12 | [assembly: AssemblyTitle("MaxMind.GeoIP2.UnitTests")] 13 | [assembly: AssemblyDescription("")] 14 | [assembly: AssemblyConfiguration("")] 15 | [assembly: AssemblyCompany("")] 16 | [assembly: AssemblyProduct("MaxMind.GeoIP2.UnitTests")] 17 | [assembly: AssemblyCopyright("Copyright © 2013-2025")] 18 | [assembly: AssemblyTrademark("")] 19 | [assembly: AssemblyCulture("")] 20 | 21 | // Setting ComVisible to false makes the types in this assembly not visible 22 | // to COM components. If you need to access a type in this assembly from 23 | // COM, set the ComVisible attribute to true on that type. 24 | 25 | [assembly: ComVisible(false)] 26 | 27 | // The following GUID is for the ID of the typelib if this project is exposed to COM 28 | 29 | [assembly: Guid("0f2242ee-c9a6-40d5-8f5f-5274054c5d30")] 30 | 31 | // Version information for an assembly consists of the following four values: 32 | // 33 | // Major Version 34 | // Minor Version 35 | // Build Number 36 | // Revision 37 | // 38 | // You can specify all the values or you can default the Build and Revision Numbers 39 | // by using the '*' as shown below: 40 | // [assembly: AssemblyVersion("1.0.*")] 41 | 42 | [assembly: AssemblyVersion("4.0.0.0")] 43 | [assembly: AssemblyFileVersion("4.0.0.0")] 44 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/ResponseHelper.cs: -------------------------------------------------------------------------------- 1 | namespace MaxMind.GeoIP2.UnitTests 2 | { 3 | internal static class ResponseHelper 4 | { 5 | public static string InsightsJson = """ 6 | { 7 | "city": { 8 | "confidence": 76, 9 | "geoname_id": 9876, 10 | "names": {"en": "Minneapolis"} 11 | }, 12 | "continent": { 13 | "code": "NA", 14 | "geoname_id": 42, 15 | "names": {"en": "North America"} 16 | }, 17 | "country": { 18 | "confidence": 99, 19 | "iso_code": "US", 20 | "geoname_id": 1, 21 | "names": {"en": "United States of America"} 22 | }, 23 | "location": { 24 | "accuracy_radius": 1500, 25 | "average_income": 50000, 26 | "latitude": 44.98, 27 | "longitude": 93.2636, 28 | "metro_code": 765, 29 | "population_density": 100, 30 | "time_zone": "America/Chicago" 31 | }, 32 | "postal": { 33 | "confidence": 33, 34 | "code": "55401" 35 | }, 36 | "registered_country": { 37 | "geoname_id": 2, 38 | "is_in_european_union": true, 39 | "iso_code": "DE", 40 | "names": {"en": "Germany"} 41 | }, 42 | "represented_country": { 43 | "geoname_id": 3, 44 | "is_in_european_union": true, 45 | "iso_code": "GB", 46 | "names": {"en": "United Kingdom"}, 47 | "type": "military" 48 | }, 49 | "subdivisions": [ 50 | { 51 | "confidence": 88, 52 | "geoname_id": 574635, 53 | "iso_code": "MN", 54 | "names": {"en": "Minnesota"} 55 | }, 56 | {"iso_code": "TT"} 57 | ], 58 | "traits": { 59 | "autonomous_system_number": 1234, 60 | "autonomous_system_organization": "AS Organization", 61 | "connection_type": "Cable/DSL", 62 | "domain": "example.com", 63 | "ip_address": "1.2.3.4", 64 | "is_anonymous": true, 65 | "is_anonymous_proxy": true, 66 | "is_anonymous_vpn": true, 67 | "is_anycast": true, 68 | "is_hosting_provider": true, 69 | "is_public_proxy": true, 70 | "is_residential_proxy": true, 71 | "is_satellite_provider": true, 72 | "is_tor_exit_node": true, 73 | "isp": "Comcast", 74 | "mobile_country_code": "310", 75 | "mobile_network_code": "004", 76 | "network": "1.2.3.0/24", 77 | "organization": "Blorg", 78 | "static_ip_score": 1.5, 79 | "user_count": 1, 80 | "user_type": "college" 81 | }, 82 | "maxmind": {"queries_remaining": 11} 83 | } 84 | """; 85 | 86 | public static string CountryJson = """ 87 | { 88 | "continent": { 89 | "code": "NA", 90 | "geoname_id": 42, 91 | "names": {"en": "North America"} 92 | }, 93 | "country": { 94 | "geoname_id": 1, 95 | "iso_code": "US", 96 | "confidence": 56, 97 | "names": {"en": "United States"} 98 | }, 99 | "registered_country": { 100 | "geoname_id": 2, 101 | "is_in_european_union": true , 102 | "iso_code": "DE", 103 | "names": {"en": "Germany"} 104 | }, 105 | "represented_country": { 106 | "geoname_id": 4, 107 | "is_in_european_union": true , 108 | "iso_code": "GB", 109 | "names": {"en": "United Kingdom"}, 110 | "type": "military" 111 | }, 112 | "traits": { 113 | "ip_address": "1.2.3.4", 114 | "is_anycast": true, 115 | "network": "1.2.3.0/24" 116 | } 117 | } 118 | """; 119 | 120 | public static string ErrorJson(string code, string message) 121 | { 122 | return $$"""{"code": "{{code}}", "error": "{{message}}"}"""; 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/ResponseTests.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Model; 4 | using MaxMind.GeoIP2.Responses; 5 | using Xunit; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.UnitTests 10 | { 11 | public class ResponseTests 12 | { 13 | [Fact] 14 | public void InsightsConstruction() 15 | { 16 | var city = new City(); 17 | var insightsReponse = new InsightsResponse(city); 18 | 19 | Assert.Equal(insightsReponse.City, city); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2.UnitTests/TestUtils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | 5 | namespace MaxMind.GeoIP2.UnitTests 6 | { 7 | internal static class TestUtils 8 | { 9 | public static string TestDirectory { get; } = GetTestDirectory(); 10 | 11 | private static string GetTestDirectory() 12 | { 13 | // check if environment variable MAXMIND_TEST_BASE_DIR is set 14 | var dbPath = Environment.GetEnvironmentVariable("MAXMIND_TEST_BASE_DIR"); 15 | 16 | if (!string.IsNullOrEmpty(dbPath)) 17 | { 18 | if (!Directory.Exists(dbPath)) 19 | { 20 | throw new Exception("Path set as environment variable MAXMIND_TEST_BASE_DIR does not exist!"); 21 | } 22 | 23 | return dbPath; 24 | } 25 | 26 | // In Microsoft.NET.Test.Sdk v15.0.0, the current working directory 27 | // is not set to project's root but instead the output directory. 28 | // see: https://github.com/Microsoft/vstest/issues/435. 29 | // 30 | // Let's change the strategry of finding the parent directory of 31 | // TestData directory by walking from cwd backwards upto the 32 | // volume's root. 33 | var currentDirectory = Directory.GetCurrentDirectory(); 34 | var currentDirectoryInfo = new DirectoryInfo(currentDirectory); 35 | 36 | do 37 | { 38 | if (currentDirectoryInfo.EnumerateDirectories("TestData*", SearchOption.AllDirectories).Any()) 39 | { 40 | return currentDirectoryInfo.FullName; 41 | } 42 | currentDirectoryInfo = currentDirectoryInfo.Parent; 43 | } while (currentDirectoryInfo?.Parent != null); 44 | 45 | return currentDirectory; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.3 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D5CCD8D4-F996-41F5-BEED-191CDF645F8A}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MaxMind.GeoIP2", "MaxMind.GeoIP2\MaxMind.GeoIP2.csproj", "{1532C665-FDC3-4A8C-BB83-B0729F547A3B}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MaxMind.GeoIP2.UnitTests", "MaxMind.GeoIP2.UnitTests\MaxMind.GeoIP2.UnitTests.csproj", "{C23F19DE-FC59-4AE7-A626-816DF28C0A97}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MaxMind.GeoIP2.Benchmark", "MaxMind.GeoIP2.Benchmark\MaxMind.GeoIP2.Benchmark.csproj", "{257FAD1A-9A52-4BA1-9869-61950F3B4687}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {1532C665-FDC3-4A8C-BB83-B0729F547A3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {1532C665-FDC3-4A8C-BB83-B0729F547A3B}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {1532C665-FDC3-4A8C-BB83-B0729F547A3B}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {1532C665-FDC3-4A8C-BB83-B0729F547A3B}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {C23F19DE-FC59-4AE7-A626-816DF28C0A97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {C23F19DE-FC59-4AE7-A626-816DF28C0A97}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {C23F19DE-FC59-4AE7-A626-816DF28C0A97}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {C23F19DE-FC59-4AE7-A626-816DF28C0A97}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {257FAD1A-9A52-4BA1-9869-61950F3B4687}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {257FAD1A-9A52-4BA1-9869-61950F3B4687}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {257FAD1A-9A52-4BA1-9869-61950F3B4687}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {257FAD1A-9A52-4BA1-9869-61950F3B4687}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | EndGlobal 37 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | <data><IncludeFilters /><ExcludeFilters /></data> 3 | <data /> -------------------------------------------------------------------------------- /MaxMind.GeoIP2/CompatibilitySuppressions.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | CP0002 6 | M:MaxMind.GeoIP2.Responses.AnonymousPlusResponse.#ctor(System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,MaxMind.Db.Network,System.String) 7 | lib/netstandard2.1/MaxMind.GeoIP2.dll 8 | lib/net8.0/MaxMind.GeoIP2.dll 9 | 10 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/CustomDictionary.xml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | injectables 7 | ip 8 | iso 9 | isp 10 | MaxMind 11 | Vpn 12 | 13 | 14 | MaxMind 15 | 16 | 17 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/AddressNotFoundException.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Runtime.Serialization; 5 | #endregion 6 | 7 | namespace MaxMind.GeoIP2.Exceptions 8 | { 9 | /// 10 | /// This exception is thrown when the IP address is not found in the database. 11 | /// This generally means that the address was a private or reserved address. 12 | /// 13 | [Serializable] 14 | public class AddressNotFoundException : GeoIP2Exception 15 | { 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | /// A message explaining the cause of the error. 20 | public AddressNotFoundException(string message) 21 | : base(message) 22 | { 23 | } 24 | 25 | /// 26 | /// Initializes a new instance of the class. 27 | /// 28 | /// A message explaining the cause of the error. 29 | /// The inner exception. 30 | public AddressNotFoundException(string message, Exception innerException) 31 | : base(message, innerException) 32 | { 33 | } 34 | 35 | /// 36 | /// Constructor for deserialization. 37 | /// 38 | /// 39 | /// 40 | #if NET8_0_OR_GREATER 41 | [Obsolete(DiagnosticId = "SYSLIB0051")] 42 | #endif 43 | protected AddressNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) 44 | { 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/AuthenticationException.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Runtime.Serialization; 5 | #endregion 6 | 7 | namespace MaxMind.GeoIP2.Exceptions 8 | { 9 | /// 10 | /// This exception is thrown when there is an authentication error. 11 | /// 12 | [Serializable] 13 | public class AuthenticationException : GeoIP2Exception 14 | { 15 | /// 16 | /// Initializes a new instance of the class. 17 | /// 18 | /// A message explaining the cause of the error. 19 | public AuthenticationException(string message) 20 | : base(message) 21 | { 22 | } 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// A message explaining the cause of the error. 28 | /// The inner exception. 29 | public AuthenticationException(string message, Exception innerException) 30 | : base(message, innerException) 31 | { 32 | } 33 | /// 34 | /// Constructor for deserialization. 35 | /// 36 | /// 37 | /// 38 | #if NET8_0_OR_GREATER 39 | [Obsolete(DiagnosticId = "SYSLIB0051")] 40 | #endif 41 | protected AuthenticationException(SerializationInfo info, StreamingContext context) : base(info, context) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/GeoIP2Exception.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Runtime.Serialization; 5 | #endregion 6 | 7 | namespace MaxMind.GeoIP2.Exceptions 8 | { 9 | /// 10 | /// This class represents a generic GeoIP2 error. All other exceptions thrown by 11 | /// the GeoIP2 API subclass this exception 12 | /// 13 | [Serializable] 14 | public class GeoIP2Exception : Exception 15 | { 16 | /// 17 | /// Initializes a new instance of the class. 18 | /// 19 | /// A message that describes the error. 20 | public GeoIP2Exception(string message) : base(message) 21 | { 22 | } 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// A message that describes the error. 28 | /// The inner exception. 29 | public GeoIP2Exception(string message, Exception innerException) 30 | : base(message, innerException) 31 | { 32 | } 33 | 34 | /// 35 | /// Constructor for deserialization. 36 | /// 37 | /// 38 | /// 39 | #if NET8_0_OR_GREATER 40 | [Obsolete(DiagnosticId = "SYSLIB0051")] 41 | #endif 42 | protected GeoIP2Exception(SerializationInfo info, StreamingContext context) : base(info, context) 43 | { 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/HttpException.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.IO; 5 | using System.Net; 6 | using System.Runtime.Serialization; 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Exceptions 10 | { 11 | /// 12 | /// This class represents an HTTP transport error. This is not an error returned 13 | /// by the web service itself. As such, it is a IOException instead of a 14 | /// GeoIP2Exception. 15 | /// 16 | [Serializable] 17 | public class HttpException : IOException 18 | { 19 | /// 20 | /// Initializes a new instance of the class. 21 | /// 22 | /// A message describing the reason why the exception was thrown. 23 | /// The HTTP status of the response that caused the exception. 24 | /// The URL queried. 25 | public HttpException(string message, HttpStatusCode httpStatus, Uri uri) 26 | : base(message) 27 | { 28 | HttpStatus = httpStatus; 29 | Uri = uri; 30 | } 31 | 32 | /// 33 | /// Initializes a new instance of the class. 34 | /// 35 | /// A message describing the reason why the exception was thrown. 36 | /// The HTTP status of the response that caused the exception. 37 | /// The URL queried. 38 | /// The underlying exception that caused this one. 39 | public HttpException(string message, HttpStatusCode httpStatus, Uri uri, Exception? innerException) 40 | : base(message, innerException) 41 | { 42 | HttpStatus = httpStatus; 43 | Uri = uri; 44 | } 45 | 46 | /// 47 | /// Constructor for deserialization. 48 | /// 49 | /// 50 | /// 51 | #if NET8_0_OR_GREATER 52 | [Obsolete(DiagnosticId = "SYSLIB0051")] 53 | #endif 54 | protected HttpException(SerializationInfo info, StreamingContext context) : base(info, context) 55 | { 56 | HttpStatus = (HttpStatusCode)(info.GetValue("MaxMind.GeoIP2.Exceptions.HttpException.HttpStatus", typeof(HttpStatusCode)) 57 | ?? throw new SerializationException("Unexcepted null HttpStatus value")); 58 | Uri = (Uri)(info.GetValue("MaxMind.GeoIP2.Exceptions.HttpException.Uri", typeof(Uri)) 59 | ?? throw new SerializationException("Unexcepted null Uri value")); 60 | } 61 | 62 | /// 63 | /// Method to serialize data. 64 | /// 65 | /// 66 | /// 67 | #if NET8_0_OR_GREATER 68 | [Obsolete(DiagnosticId = "SYSLIB0051")] 69 | #endif 70 | public override void GetObjectData(SerializationInfo info, StreamingContext context) 71 | { 72 | base.GetObjectData(info, context); 73 | 74 | info.AddValue("MaxMind.GeoIP2.Exceptions.HttpException.HttpStatus", HttpStatus, typeof(HttpStatusCode)); 75 | info.AddValue("MaxMind.GeoIP2.Exceptions.HttpException.Uri", Uri, typeof(Uri)); 76 | } 77 | 78 | /// 79 | /// The HTTP status code returned by the web service. 80 | /// 81 | public HttpStatusCode HttpStatus { get; } 82 | 83 | /// 84 | /// The URI queried by the web service. 85 | /// 86 | public Uri Uri { get; } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/InvalidRequestException.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Runtime.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Exceptions 9 | { 10 | /// 11 | /// This class represents a non-specific error returned by MaxMind's GeoIP2 web 12 | /// service. This occurs when the web service is up and responding to requests, 13 | /// but the request sent was invalid in some way. 14 | /// 15 | [Serializable] 16 | public class InvalidRequestException : GeoIP2Exception 17 | { 18 | /// 19 | /// Initializes a new instance of the class. 20 | /// 21 | /// A message explaining the cause of the error. 22 | /// The error code returned by the web service. 23 | /// The URL queried. 24 | public InvalidRequestException(string message, string code, Uri uri) 25 | : base(message) 26 | { 27 | Code = code; 28 | Uri = uri; 29 | } 30 | 31 | 32 | /// 33 | /// Constructor for deserialization. 34 | /// 35 | /// 36 | /// 37 | #if NET8_0_OR_GREATER 38 | [Obsolete(DiagnosticId = "SYSLIB0051")] 39 | #endif 40 | protected InvalidRequestException(SerializationInfo info, StreamingContext context) : base(info, context) 41 | { 42 | Code = info.GetString("MaxMind.GeoIP2.Exceptions.InvalidRequestException.Code") 43 | ?? throw new SerializationException("Unexcepted null Code value"); 44 | Uri = (Uri)(info.GetValue("MaxMind.GeoIP2.Exceptions.InvalidRequestException.Uri", typeof(Uri)) 45 | ?? throw new SerializationException("Unexcepted null Uri value")); 46 | } 47 | 48 | /// 49 | /// Method to serialize data. 50 | /// 51 | /// 52 | /// 53 | #if NET8_0_OR_GREATER 54 | [Obsolete(DiagnosticId = "SYSLIB0051")] 55 | #endif 56 | public override void GetObjectData(SerializationInfo info, StreamingContext context) 57 | { 58 | base.GetObjectData(info, context); 59 | 60 | info.AddValue("MaxMind.GeoIP2.Exceptions.InvalidRequestException.Code", Code); 61 | info.AddValue("MaxMind.GeoIP2.Exceptions.InvalidRequestException.Uri", Uri, typeof(Uri)); 62 | } 63 | 64 | /// 65 | /// The error code returned by the web service. 66 | /// 67 | public string Code { get; } 68 | 69 | /// 70 | /// The URI queried by the web service. 71 | /// 72 | public Uri Uri { get; } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/OutOfQueriesException.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Runtime.Serialization; 5 | #endregion 6 | 7 | namespace MaxMind.GeoIP2.Exceptions 8 | { 9 | /// 10 | /// This exception is thrown when your account does not have any queries remaining for the called service. 11 | /// 12 | [Serializable] 13 | public class OutOfQueriesException : GeoIP2Exception 14 | { 15 | /// 16 | /// Initializes a new instance of the class. 17 | /// 18 | /// A message that describes the error. 19 | public OutOfQueriesException(string message) 20 | : base(message) 21 | { 22 | } 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// A message explaining the cause of the error. 28 | /// The inner exception. 29 | public OutOfQueriesException(string message, Exception innerException) 30 | : base(message, innerException) 31 | { 32 | } 33 | 34 | /// 35 | /// Constructor for deserialization. 36 | /// 37 | /// 38 | /// 39 | #if NET8_0_OR_GREATER 40 | [Obsolete(DiagnosticId = "SYSLIB0051")] 41 | #endif 42 | protected OutOfQueriesException(SerializationInfo info, StreamingContext context) : base(info, context) 43 | { 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Exceptions/PermissionRequiredException.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Runtime.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Exceptions 9 | { 10 | /// 11 | /// This class represents an authentication error. 12 | /// 13 | [Serializable] 14 | public class PermissionRequiredException : GeoIP2Exception 15 | { 16 | /// 17 | /// Constructor. 18 | /// 19 | /// Exception message. 20 | public PermissionRequiredException(string message) : base(message) 21 | { 22 | } 23 | 24 | /// 25 | /// Constructor. 26 | /// 27 | /// Exception message. 28 | /// The underlying exception that caused this one. 29 | public PermissionRequiredException(string message, Exception innerException) 30 | : base(message, innerException) 31 | { 32 | } 33 | 34 | /// 35 | /// Constructor for deserialization. 36 | /// 37 | /// 38 | /// 39 | #if NET8_0_OR_GREATER 40 | [Obsolete(DiagnosticId = "SYSLIB0051")] 41 | #endif 42 | protected PermissionRequiredException(SerializationInfo info, StreamingContext context) : base(info, context) 43 | { 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/GlobalSuppressions.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | 3 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.Country.#ctor(System.Nullable{System.Int32},System.Nullable{System.Int64},System.Boolean,System.String,System.Collections.Generic.IReadOnlyDictionary{System.String,System.String},System.Collections.Generic.IReadOnlyList{System.String})")] 4 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.Location.#ctor(System.Nullable{System.Int32},System.Nullable{System.Double},System.Nullable{System.Double},System.Nullable{System.Int32},System.String)")] 5 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.RepresentedCountry.#ctor(System.String,System.Nullable{System.Int32},System.Nullable{System.Int64},System.Boolean,System.String,System.Collections.Generic.IReadOnlyDictionary{System.String,System.String},System.Collections.Generic.IReadOnlyList{System.String})")] 6 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Responses.CityResponse.#ctor(MaxMind.GeoIP2.Model.City,MaxMind.GeoIP2.Model.Continent,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.Location,MaxMind.GeoIP2.Model.MaxMind,MaxMind.GeoIP2.Model.Postal,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.RepresentedCountry,System.Collections.Generic.IReadOnlyList{MaxMind.GeoIP2.Model.Subdivision},MaxMind.GeoIP2.Model.Traits)")] 7 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Responses.InsightsResponse.#ctor(MaxMind.GeoIP2.Model.City,MaxMind.GeoIP2.Model.Continent,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.Location,MaxMind.GeoIP2.Model.MaxMind,MaxMind.GeoIP2.Model.Postal,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.RepresentedCountry,System.Collections.Generic.IReadOnlyList{MaxMind.GeoIP2.Model.Subdivision},MaxMind.GeoIP2.Model.Traits)")] 8 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.Continent.#ctor(System.String,System.Nullable{System.Int64},System.Collections.Generic.IReadOnlyDictionary{System.String,System.String},System.Collections.Generic.IReadOnlyList{System.String})")] 9 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.Subdivision.#ctor(System.Nullable{System.Int32},System.Nullable{System.Int64},System.String,System.Collections.Generic.IReadOnlyDictionary{System.String,System.String},System.Collections.Generic.IReadOnlyList{System.String})")] 10 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.Postal.#ctor(System.String,System.Nullable{System.Int32})")] 11 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Responses.AbstractCityResponse.#ctor(MaxMind.GeoIP2.Model.City,MaxMind.GeoIP2.Model.Continent,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.Location,MaxMind.GeoIP2.Model.MaxMind,MaxMind.GeoIP2.Model.Postal,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.RepresentedCountry,System.Collections.Generic.IReadOnlyList{MaxMind.GeoIP2.Model.Subdivision},MaxMind.GeoIP2.Model.Traits)")] 12 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Responses.CountryResponse.#ctor(MaxMind.GeoIP2.Model.Continent,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.MaxMind,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.RepresentedCountry,MaxMind.GeoIP2.Model.Traits)")] 13 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Model.City.#ctor(System.Nullable{System.Int32},System.Nullable{System.Int64},System.Collections.Generic.IReadOnlyDictionary{System.String,System.String},System.Collections.Generic.IReadOnlyList{System.String})")] 14 | [assembly: SuppressMessage("Blocker Code Smell", "S3427:Method overloads with default parameter values should not overlap ", Justification = "", Scope = "member", Target = "~M:MaxMind.GeoIP2.Responses.AbstractCountryResponse.#ctor(MaxMind.GeoIP2.Model.Continent,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.MaxMind,MaxMind.GeoIP2.Model.Country,MaxMind.GeoIP2.Model.RepresentedCountry,MaxMind.GeoIP2.Model.Traits)")] 15 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Http/Client.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Threading.Tasks; 9 | 10 | #endregion 11 | 12 | namespace MaxMind.GeoIP2.Http 13 | { 14 | /// 15 | /// This abstraction existed so that we could support both HttpClient and 16 | /// WebRequest. After we drop .NET Standard 2.1 support, we should get rid 17 | /// of this abstraction. Doing so will likely help us reduce unnecessary 18 | /// allocations. 19 | /// 20 | internal class Client : IDisposable 21 | { 22 | private readonly HttpClient _httpClient; 23 | private bool _disposed; 24 | 25 | public Client( 26 | string auth, 27 | int timeout, 28 | ProductInfoHeaderValue userAgent, 29 | HttpClient httpClient 30 | ) 31 | { 32 | httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth); 33 | httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 34 | httpClient.DefaultRequestHeaders.UserAgent.Add(userAgent); 35 | httpClient.Timeout = TimeSpan.FromMilliseconds(timeout); 36 | 37 | _httpClient = httpClient; 38 | } 39 | 40 | #if !NETSTANDARD2_0 && !NETSTANDARD2_1 41 | public Response Get(Uri uri) 42 | { 43 | var message = new HttpRequestMessage(HttpMethod.Get, uri); 44 | var response = _httpClient.Send(message); 45 | 46 | // Reading to a byte array isn't ideal, but changing this would require 47 | // more refactoring and probably introducing completely separate code 48 | // paths for async vs sync. Hopefully we can get rid of the sync code at 49 | // some point instead. 50 | var ms = new MemoryStream(); 51 | response.Content.ReadAsStream().CopyTo(ms); 52 | var content = ms.ToArray(); 53 | var contentType = response.Content.Headers.GetValues("Content-Type").FirstOrDefault(); 54 | 55 | return new Response(uri, response.StatusCode, contentType, content); 56 | } 57 | #endif 58 | public async Task GetAsync(Uri uri) 59 | { 60 | var response = await _httpClient.GetAsync(uri).ConfigureAwait(false); 61 | 62 | // Reading to a byte array isn't ideal, but changing this would require 63 | // more refactoring and probably introducing completely separate code 64 | // paths for async vs sync. Hopefully we can get rid of the sync code at 65 | // some point instead. 66 | var content = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); 67 | var contentType = response.Content.Headers.GetValues("Content-Type").FirstOrDefault(); 68 | 69 | return new Response(uri, response.StatusCode, contentType, content); 70 | } 71 | 72 | public void Dispose() 73 | { 74 | Dispose(true); 75 | GC.SuppressFinalize(this); 76 | } 77 | 78 | protected virtual void Dispose(bool disposing) 79 | { 80 | if (_disposed) 81 | return; 82 | 83 | if (disposing) 84 | { 85 | _httpClient.Dispose(); 86 | } 87 | 88 | _disposed = true; 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Http/ISyncClient.cs: -------------------------------------------------------------------------------- 1 | #if NETSTANDARD2_0 || NETSTANDARD2_1 2 | 3 | #region 4 | 5 | using System; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Http 10 | { 11 | internal interface ISyncClient 12 | { 13 | Response Get(Uri uri); 14 | } 15 | } 16 | #endif -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Http/Response.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Net; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Http 9 | { 10 | internal class Response(Uri requestUri, HttpStatusCode statusCode, string? contentType, byte[] content) 11 | { 12 | internal HttpStatusCode StatusCode { get; } = statusCode; 13 | internal Uri RequestUri { get; } = requestUri; 14 | internal byte[] Content { get; } = content; 15 | internal string? ContentType { get; } = contentType; 16 | 17 | internal static object Create() 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Http/SyncClient.cs: -------------------------------------------------------------------------------- 1 | #if NETSTANDARD2_0 || NETSTANDARD2_1 2 | 3 | #region 4 | 5 | using MaxMind.GeoIP2.Exceptions; 6 | using System; 7 | using System.Net; 8 | using System.Net.Http.Headers; 9 | 10 | #endregion 11 | 12 | namespace MaxMind.GeoIP2.Http 13 | { 14 | internal class SyncClient : ISyncClient 15 | { 16 | private readonly string _auth; 17 | private readonly int _timeout; 18 | private readonly string _userAgent; 19 | 20 | public SyncClient( 21 | string auth, 22 | int timeout, 23 | ProductInfoHeaderValue userAgent 24 | ) 25 | { 26 | _auth = auth; 27 | _timeout = timeout; 28 | _userAgent = userAgent.ToString(); 29 | } 30 | 31 | public Response Get(Uri uri) 32 | { 33 | var request = (HttpWebRequest)WebRequest.Create(uri); 34 | request.Timeout = _timeout; 35 | request.UserAgent = _userAgent; 36 | request.Headers["Authorization"] = $"Basic {_auth}"; 37 | 38 | HttpWebResponse response; 39 | try 40 | { 41 | response = (HttpWebResponse)request.GetResponse(); 42 | } 43 | catch (WebException e) 44 | { 45 | if (e.Status != WebExceptionStatus.ProtocolError || e.Response == null) 46 | { 47 | throw new HttpException( 48 | $"Error received while making request: {e.Message}", 49 | 0, uri, e); 50 | } 51 | response = (HttpWebResponse)e.Response; 52 | } 53 | 54 | using var responseStream = response.GetResponseStream(); 55 | using var stream = new System.IO.MemoryStream(); 56 | responseStream.CopyTo(stream); 57 | 58 | // The creation of an additional array with ToArray() isn't ideal, 59 | // but presumably most people who care about performance are using 60 | // the Async methods anyway. We can't use the underlying buffer as 61 | // that has null bytes at the end. Potentially we could refactor 62 | // the code to use spans. 63 | return new Response(uri, response.StatusCode, response.ContentType, 64 | stream.ToArray()); 65 | } 66 | } 67 | } 68 | 69 | #endif -------------------------------------------------------------------------------- /MaxMind.GeoIP2/IGeoIP2DatabaseReader.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using MaxMind.GeoIP2.Http; 5 | using MaxMind.GeoIP2.Responses; 6 | using System.Net; 7 | 8 | #endregion 9 | 10 | namespace MaxMind.GeoIP2 11 | { 12 | /// 13 | /// Interface for database reader 14 | /// 15 | public interface IGeoIP2DatabaseReader : IGeoIP2Provider 16 | { 17 | /// 18 | /// The metadata for the open MaxMind DB file. 19 | /// 20 | Metadata Metadata { get; } 21 | 22 | /// 23 | /// Look up an IP address in a GeoIP2 Anonymous IP. 24 | /// 25 | /// The IP address. 26 | /// An 27 | AnonymousIPResponse AnonymousIP(IPAddress ipAddress); 28 | 29 | /// 30 | /// Look up an IP address in a GeoIP2 Anonymous IP. 31 | /// 32 | /// The IP address. 33 | /// An 34 | AnonymousIPResponse AnonymousIP(string ipAddress); 35 | 36 | /// 37 | /// Tries to lookup an for the specified IP address. 38 | /// 39 | /// The IP address. 40 | /// The . 41 | /// A describing whether the IP address was found. 42 | bool TryAnonymousIP(IPAddress ipAddress, out AnonymousIPResponse? response); 43 | 44 | /// 45 | /// Tries to lookup an for the specified IP address. 46 | /// 47 | /// The IP address. 48 | /// The . 49 | /// A describing whether the IP address was found. 50 | bool TryAnonymousIP(string ipAddress, out AnonymousIPResponse? response); 51 | 52 | /// 53 | /// Returns an for the specified IP address. 54 | /// 55 | /// The IP address. 56 | /// An 57 | AsnResponse Asn(IPAddress ipAddress); 58 | 59 | /// 60 | /// Returns an for the specified IP address. 61 | /// 62 | /// The IP address. 63 | /// An 64 | AsnResponse Asn(string ipAddress); 65 | 66 | /// 67 | /// Tries to lookup an for the specified IP address. 68 | /// 69 | /// The IP address. 70 | /// The . 71 | /// A describing whether the IP address was found. 72 | bool TryAsn(IPAddress ipAddress, out AsnResponse? response); 73 | 74 | /// 75 | /// Tries to lookup an for the specified IP address. 76 | /// 77 | /// The IP address. 78 | /// The . 79 | /// A describing whether the IP address was found. 80 | bool TryAsn(string ipAddress, out AsnResponse? response); 81 | 82 | /// 83 | /// Tries to lookup a for the specified IP address. 84 | /// 85 | /// The IP address. 86 | /// The . 87 | /// A describing whether the IP address was found. 88 | bool TryCity(IPAddress ipAddress, out CityResponse? response); 89 | 90 | /// 91 | /// Tries to lookup a for the specified IP address. 92 | /// 93 | /// The IP address. 94 | /// The . 95 | /// A describing whether the IP address was found. 96 | bool TryCity(string ipAddress, out CityResponse? response); 97 | 98 | /// 99 | /// Tries to lookup a for the specified IP address. 100 | /// 101 | /// The IP address. 102 | /// The . 103 | /// A describing whether the IP address was found. 104 | bool TryCountry(IPAddress ipAddress, out CountryResponse? response); 105 | 106 | /// 107 | /// Tries to lookup a for the specified IP address. 108 | /// 109 | /// The IP address. 110 | /// The . 111 | /// A describing whether the IP address was found. 112 | bool TryCountry(string ipAddress, out CountryResponse? response); 113 | 114 | /// 115 | /// Returns an for the specified IP address. 116 | /// 117 | /// The IP address. 118 | /// An 119 | ConnectionTypeResponse ConnectionType(IPAddress ipAddress); 120 | 121 | /// 122 | /// Returns an for the specified IP address. 123 | /// 124 | /// The IP address. 125 | /// An 126 | ConnectionTypeResponse ConnectionType(string ipAddress); 127 | 128 | /// 129 | /// Tries to lookup a for the specified IP address. 130 | /// 131 | /// The IP address. 132 | /// The . 133 | /// A describing whether the IP address was found. 134 | bool TryConnectionType(IPAddress ipAddress, out ConnectionTypeResponse? response); 135 | 136 | /// 137 | /// Tries to lookup a for the specified IP address. 138 | /// 139 | /// The IP address. 140 | /// The . 141 | /// A describing whether the IP address was found. 142 | bool TryConnectionType(string ipAddress, out ConnectionTypeResponse? response); 143 | 144 | /// 145 | /// Returns an for the specified IP address. 146 | /// 147 | /// The IP address. 148 | /// An 149 | DomainResponse Domain(IPAddress ipAddress); 150 | 151 | /// 152 | /// Returns an for the specified IP address. 153 | /// 154 | /// The IP address. 155 | /// An 156 | DomainResponse Domain(string ipAddress); 157 | 158 | /// 159 | /// Tries to lookup a for the specified IP address. 160 | /// 161 | /// The IP address. 162 | /// The . 163 | /// A describing whether the IP address was found. 164 | bool TryDomain(IPAddress ipAddress, out DomainResponse? response); 165 | 166 | /// 167 | /// Tries to lookup a for the specified IP address. 168 | /// 169 | /// The IP address. 170 | /// The . 171 | /// A describing whether the IP address was found. 172 | bool TryDomain(string ipAddress, out DomainResponse? response); 173 | 174 | /// 175 | /// Returns an for the specified IP address. 176 | /// 177 | /// The IP address. 178 | /// An 179 | EnterpriseResponse Enterprise(IPAddress ipAddress); 180 | 181 | /// 182 | /// Returns an for the specified IP address. 183 | /// 184 | /// The IP address. 185 | /// An 186 | EnterpriseResponse Enterprise(string ipAddress); 187 | 188 | /// 189 | /// Tries to lookup a for the specified IP address. 190 | /// 191 | /// The IP address. 192 | /// The . 193 | /// A describing whether the IP address was found. 194 | bool TryEnterprise(IPAddress ipAddress, out EnterpriseResponse? response); 195 | 196 | /// 197 | /// Tries to lookup a for the specified IP address. 198 | /// 199 | /// The IP address. 200 | /// The . 201 | /// A describing whether the IP address was found. 202 | bool TryEnterprise(string ipAddress, out EnterpriseResponse? response); 203 | 204 | /// 205 | /// Returns an for the specified IP address. 206 | /// 207 | /// The IP address. 208 | /// An 209 | IspResponse Isp(IPAddress ipAddress); 210 | 211 | /// 212 | /// Returns an for the specified IP address. 213 | /// 214 | /// The IP address. 215 | /// An 216 | IspResponse Isp(string ipAddress); 217 | 218 | /// 219 | /// Tries to lookup an for the specified IP address. 220 | /// 221 | /// The IP address. 222 | /// The . 223 | /// A describing whether the IP address was found. 224 | bool TryIsp(IPAddress ipAddress, out IspResponse? response); 225 | 226 | /// 227 | /// Tries to lookup an for the specified IP address. 228 | /// 229 | /// The IP address. 230 | /// The . 231 | /// A describing whether the IP address was found. 232 | bool TryIsp(string ipAddress, out IspResponse? response); 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/IGeoIP2Provider.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Responses; 4 | using System.Net; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2 9 | { 10 | /// 11 | /// This class provides the interface implemented by both 12 | /// and . 13 | /// 14 | public interface IGeoIP2Provider 15 | { 16 | /// 17 | /// Returns an for the specified ip address. 18 | /// 19 | /// The ip address. 20 | /// An 21 | CountryResponse Country(string ipAddress); 22 | 23 | /// 24 | /// Returns an for the specified ip address. 25 | /// 26 | /// The ip address. 27 | /// An 28 | CountryResponse Country(IPAddress ipAddress); 29 | 30 | /// 31 | /// Returns an for the specified ip address. 32 | /// 33 | /// The ip address. 34 | /// An 35 | CityResponse City(string ipAddress); 36 | 37 | /// 38 | /// Returns an for the specified ip address. 39 | /// 40 | /// The ip address. 41 | /// An 42 | CityResponse City(IPAddress ipAddress); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/IGeoIP2WebServicesClient.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Responses; 4 | using System.Net; 5 | using System.Threading.Tasks; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2 10 | { 11 | /// 12 | /// Interface for web-service client 13 | /// 14 | public interface IGeoIP2WebServicesClient : IGeoIP2Provider 15 | { 16 | /// 17 | /// Returns an for the requesting IP address. 18 | /// 19 | /// An 20 | CountryResponse Country(); 21 | 22 | /// 23 | /// Returns an for the requesting IP address. 24 | /// 25 | /// An 26 | CityResponse City(); 27 | 28 | /// 29 | /// Returns an for the specified IP address. 30 | /// 31 | /// The IP address. 32 | /// An 33 | InsightsResponse Insights(string ipAddress); 34 | 35 | /// 36 | /// Returns an for the specified IP address. 37 | /// 38 | /// The IP address. 39 | /// An 40 | InsightsResponse Insights(IPAddress ipAddress); 41 | 42 | /// 43 | /// Returns an for the requesting IP address. 44 | /// 45 | /// An 46 | InsightsResponse Insights(); 47 | 48 | /// 49 | /// Asynchronously query the GeoIP2 Country web service for the specified IP address. 50 | /// 51 | /// The IP address. 52 | /// Task that produces an object modeling the Country response 53 | Task CountryAsync(string ipAddress); 54 | 55 | /// 56 | /// Asynchronously query the GeoIP2 Country web service for the specified IP address. 57 | /// 58 | /// The IP address. 59 | /// Task that produces an object modeling the Country response 60 | Task CountryAsync(IPAddress ipAddress); 61 | 62 | /// 63 | /// Asynchronously query the GeoIP2 Country web service for the requesting IP address. 64 | /// 65 | /// Task that produces an object modeling the Country response 66 | Task CountryAsync(); 67 | 68 | /// 69 | /// Asynchronously query the GeoIP2 City Plus web service for the specified IP address. 70 | /// 71 | /// The IP address. 72 | /// Task that produces an object modeling the City Plus response 73 | Task CityAsync(string ipAddress); 74 | 75 | /// 76 | /// Asynchronously query the GeoIP2 City Plus web service for the specified IP address. 77 | /// 78 | /// The IP address. 79 | /// Task that produces an object modeling the City Plus response 80 | Task CityAsync(IPAddress ipAddress); 81 | 82 | /// 83 | /// Asynchronously query the GeoIP2 City Plus web service for the requesting IP address. 84 | /// 85 | /// Task that produces an object modeling the City Plus response 86 | Task CityAsync(); 87 | 88 | /// 89 | /// Asynchronously query the GeoIP2 Insights web service for the specified IP address. 90 | /// 91 | /// The IP address. 92 | /// Task that produces an object modeling the Insights response 93 | Task InsightsAsync(string ipAddress); 94 | 95 | /// 96 | /// Asynchronously query the GeoIP2 Insights web service for the specified IP address. 97 | /// 98 | /// The IP address. 99 | /// Task that produces an object modeling the Insights response 100 | Task InsightsAsync(IPAddress ipAddress); 101 | 102 | /// 103 | /// Asynchronously query the GeoIP2 Insights web service for the requesting IP address. 104 | /// 105 | /// Task that produces an object modeling the Insights response 106 | Task InsightsAsync(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/MaxMind.GeoIP2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | MaxMind GeoIP2 Database Reader and Web Service Client 5 | 5.3.0 6 | net9.0;net8.0;netstandard2.1;netstandard2.0 7 | true 8 | MaxMind.GeoIP2 9 | ../MaxMind.snk 10 | true 11 | true 12 | MaxMind.GeoIP2 13 | maxmind;ip;geoip;geoip2;geolocation;maxmind;ipv4;ipv6 14 | MaxMind-logo.png 15 | README.md 16 | https://github.com/maxmind/GeoIP2-dotnet 17 | Apache-2.0 18 | true 19 | git 20 | https://github.com/maxmind/GeoIP2-dotnet 21 | false 22 | false 23 | false 24 | false 25 | false 26 | false 27 | false 28 | false 29 | false 30 | 13.0 31 | enable 32 | latest 33 | true 34 | true 35 | true 36 | 37 | 38 | 39 | 9999 40 | 41 | 42 | 43 | 9999 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 9.0.0 54 | 55 | 56 | 57 | 58 | 59 | True 60 | 61 | 62 | 63 | True 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/MaxMind.GeoIP2.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $title$ 7 | $author$ 8 | $author$ 9 | https://www.apache.org/licenses/LICENSE-2.0.html 10 | https://github.com/maxmind/GeoIP2-dotnet 11 | false 12 | $description$ 13 | Copyright 2015 14 | MaxMind GeoIP GeoIP2 IP database geolocation 15 | 16 | 17 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/City.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Collections.Generic; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Model 10 | { 11 | /// 12 | /// City-level data associated with an IP address. 13 | /// 14 | /// 15 | /// Do not use any of the city names as a database or dictionary 16 | /// key. Use the instead. 17 | /// 18 | public class City : NamedEntity 19 | { 20 | /// 21 | /// Constructor 22 | /// 23 | public City() 24 | { 25 | } 26 | 27 | /// 28 | /// Constructor 29 | /// 30 | [Constructor] 31 | public City(int? confidence = null, 32 | [Parameter("geoname_id")] long? geoNameId = null, 33 | IReadOnlyDictionary? names = null, 34 | IReadOnlyList? locales = null) 35 | : base(geoNameId, names, locales) 36 | { 37 | Confidence = confidence; 38 | } 39 | 40 | /// 41 | /// A value from 0-100 indicating MaxMind's confidence that the city 42 | /// is correct. This value is only set when using the Insights 43 | /// web service or the Enterprise database. 44 | /// 45 | [JsonInclude] 46 | [JsonPropertyName("confidence")] 47 | public int? Confidence { get; internal set; } 48 | } 49 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/Continent.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Collections.Generic; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Model 10 | { 11 | /// 12 | /// Contains data for the continent record associated with an IP address. 13 | /// Do not use any of the continent names as a database or dictionary 14 | /// key. Use the or 15 | /// instead. 16 | /// 17 | public class Continent : NamedEntity 18 | { 19 | /// 20 | /// Constructor 21 | /// 22 | public Continent() 23 | { 24 | } 25 | 26 | /// 27 | /// Constructor 28 | /// 29 | [Constructor] 30 | public Continent( 31 | string? code = null, 32 | [Parameter("geoname_id")] long? geoNameId = null, 33 | IReadOnlyDictionary? names = null, 34 | IReadOnlyList? locales = null) 35 | : base(geoNameId, names, locales) 36 | { 37 | Code = code; 38 | } 39 | 40 | /// 41 | /// A two character continent code like "NA" (North America) or "OC" 42 | /// (Oceania). 43 | /// 44 | [JsonInclude] 45 | [JsonPropertyName("code")] 46 | public string? Code { get; internal set; } 47 | } 48 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/Country.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Collections.Generic; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Model 10 | { 11 | /// 12 | /// Contains data for the country record associated with an IP address. 13 | /// Do not use any of the country names as a database or dictionary 14 | /// key. Use the or 15 | /// instead. 16 | /// 17 | public class Country : NamedEntity 18 | { 19 | /// 20 | /// Constructor 21 | /// 22 | public Country() 23 | { 24 | } 25 | 26 | /// 27 | /// Constructor 28 | /// 29 | [Constructor] 30 | public Country( 31 | int? confidence = null, 32 | [Parameter("geoname_id")] long? geoNameId = null, 33 | [Parameter("is_in_european_union")] bool isInEuropeanUnion = false, 34 | [Parameter("iso_code")] string? isoCode = null, 35 | IReadOnlyDictionary? names = null, 36 | IReadOnlyList? locales = null) 37 | : base(geoNameId, names, locales) 38 | { 39 | Confidence = confidence; 40 | IsoCode = isoCode; 41 | IsInEuropeanUnion = isInEuropeanUnion; 42 | } 43 | 44 | /// 45 | /// A value from 0-100 indicating MaxMind's confidence that the country 46 | /// is correct. This value is only set when using the Insights 47 | /// web service or the Enterprise database. 48 | /// 49 | [JsonInclude] 50 | [JsonPropertyName("confidence")] 51 | public int? Confidence { get; internal set; } 52 | 53 | /// 54 | /// This is true if the country is a member state of the 55 | /// European Union. This is available from all location 56 | /// services and databases. 57 | /// 58 | [JsonInclude] 59 | [JsonPropertyName("is_in_european_union")] 60 | public bool IsInEuropeanUnion { get; internal set; } 61 | 62 | /// 63 | /// The 64 | /// 66 | /// two-character ISO 67 | /// 3166-1 alpha code 68 | /// 69 | /// for the country. 70 | /// 71 | [JsonInclude] 72 | [JsonPropertyName("iso_code")] 73 | public string? IsoCode { get; internal set; } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/Location.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Model 10 | { 11 | /// 12 | /// Contains data for the location record associated with an IP address. 13 | /// 14 | public class Location 15 | { 16 | /// 17 | /// Constructor 18 | /// 19 | public Location() 20 | { 21 | } 22 | 23 | /// 24 | /// Constructor 25 | /// 26 | [Constructor] 27 | public Location( 28 | [Parameter("accuracy_radius")] int? accuracyRadius = null, 29 | double? latitude = null, 30 | double? longitude = null, 31 | [Parameter("metro_code")] int? metroCode = null, 32 | [Parameter("time_zone")] string? timeZone = null) 33 | { 34 | AccuracyRadius = accuracyRadius; 35 | Latitude = latitude; 36 | Longitude = longitude; 37 | #pragma warning disable 618 38 | MetroCode = metroCode; 39 | #pragma warning restore 618 40 | TimeZone = timeZone; 41 | } 42 | 43 | /// 44 | /// The approximate accuracy radius in kilometers around the 45 | /// latitude and longitude for the IP address. This is the radius 46 | /// where we have a 67% confidence that the device using the IP 47 | /// address resides within the circle centered at the latitude and 48 | /// longitude with the provided radius. 49 | /// 50 | [JsonInclude] 51 | [JsonPropertyName("accuracy_radius")] 52 | public int? AccuracyRadius { get; internal set; } 53 | 54 | /// 55 | /// The average income in US dollars associated with the IP address. 56 | /// 57 | [JsonInclude] 58 | [JsonPropertyName("average_income")] 59 | public int? AverageIncome { get; internal set; } 60 | 61 | /// 62 | /// Determines whether both the Latitude 63 | /// and Longitude have values. 64 | /// 65 | [JsonIgnore] 66 | public bool HasCoordinates => Latitude.HasValue && Longitude.HasValue; 67 | 68 | /// 69 | /// The approximate latitude of the location associated with the 70 | /// IP address. This value is not precise and should not be used 71 | /// to identify a particular address or household. 72 | /// 73 | [JsonInclude] 74 | [JsonPropertyName("latitude")] 75 | public double? Latitude { get; internal set; } 76 | 77 | /// 78 | /// The approximate longitude of the location associated with the 79 | /// IP address. This value is not precise and should not be used 80 | /// to identify a particular address or household. 81 | /// 82 | [JsonInclude] 83 | [JsonPropertyName("longitude")] 84 | public double? Longitude { get; internal set; } 85 | 86 | /// 87 | /// The metro code is a no-longer-maintained code for targeting 88 | /// advertisements in Google. 89 | /// 90 | [JsonInclude] 91 | [JsonPropertyName("metro_code")] 92 | [Obsolete("Code values are no longer maintained.")] 93 | public int? MetroCode { get; internal set; } 94 | 95 | /// 96 | /// The estimated number of people per square kilometer. 97 | /// 98 | [JsonInclude] 99 | [JsonPropertyName("population_density")] 100 | public int? PopulationDensity { get; internal set; } 101 | 102 | /// 103 | /// The time zone associated with location, as specified by the 104 | /// 106 | /// IANA Time Zone 107 | /// Database 108 | /// 109 | /// , e.g., "America/New_York". 110 | /// 111 | [JsonInclude] 112 | [JsonPropertyName("time_zone")] 113 | public string? TimeZone { get; internal set; } 114 | 115 | /// 116 | /// Returns a that represents this instance. 117 | /// 118 | /// 119 | /// A that represents this instance. 120 | /// 121 | public override string ToString() 122 | { 123 | return "Location [ " 124 | + (AccuracyRadius.HasValue ? "AccuracyRadius=" + AccuracyRadius + ", " : string.Empty) 125 | + (Latitude.HasValue ? "Latitude=" + Latitude + ", " : string.Empty) 126 | + (Longitude.HasValue ? "Longitude=" + Longitude + ", " : string.Empty) 127 | #pragma warning disable 618 128 | + (MetroCode.HasValue ? "MetroCode=" + MetroCode + ", " : string.Empty) 129 | #pragma warning restore 618 130 | + (TimeZone != null ? "TimeZone=" + TimeZone : "") + "]"; 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/MaxMind.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Text.Json.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Model 9 | { 10 | /// 11 | /// Contains data related to your MaxMind account. 12 | /// 13 | public class MaxMind 14 | { 15 | /// 16 | /// Constructor 17 | /// 18 | public MaxMind() 19 | { 20 | } 21 | 22 | /// 23 | /// Constructor 24 | /// 25 | [Constructor] 26 | public MaxMind([Parameter("queries_remaining")] int queriesRemaining) 27 | { 28 | QueriesRemaining = queriesRemaining; 29 | } 30 | 31 | /// 32 | /// The number of remaining queries in your account for the web 33 | /// service end point. This will be null when using a local 34 | /// database. 35 | /// 36 | [JsonInclude] 37 | [JsonPropertyName("queries_remaining")] 38 | public int? QueriesRemaining { get; internal set; } 39 | 40 | /// 41 | /// Returns a that represents this instance. 42 | /// 43 | /// 44 | /// A that represents this instance. 45 | /// 46 | public override string ToString() 47 | { 48 | return $"MaxMind [ QueriesRemaining={QueriesRemaining} ]"; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/NamedEntity.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Collections.Generic; 5 | using System.Collections.ObjectModel; 6 | using System.Linq; 7 | using System.Text.Json.Serialization; 8 | 9 | #endregion 10 | 11 | namespace MaxMind.GeoIP2.Model 12 | { 13 | /// 14 | /// Abstract class for records with name maps. 15 | /// 16 | public abstract class NamedEntity 17 | { 18 | /// 19 | /// Constructor 20 | /// 21 | [Constructor] 22 | protected NamedEntity(long? geoNameId = null, IReadOnlyDictionary? names = null, 23 | IReadOnlyList? locales = null) 24 | { 25 | Names = names ?? new ReadOnlyDictionary(new Dictionary()); 26 | GeoNameId = geoNameId; 27 | Locales = locales ?? new List { "en" }.AsReadOnly(); 28 | } 29 | 30 | /// 31 | /// A 32 | /// from locale codes to the name in that locale. Don't use any of 33 | /// these names as a database or dictionary key. Use the 34 | /// 36 | /// or relevant code instead. 37 | /// 38 | [JsonInclude] 39 | [JsonPropertyName("names")] 40 | public IReadOnlyDictionary Names { get; internal set; } 41 | 42 | /// 43 | /// The GeoName ID for the city. 44 | /// 45 | [JsonInclude] 46 | [JsonPropertyName("geoname_id")] 47 | public long? GeoNameId { get; internal set; } 48 | 49 | /// 50 | /// Gets or sets the locales specified by the user. 51 | /// 52 | [JsonIgnore] 53 | protected internal IReadOnlyList Locales { get; set; } 54 | 55 | /// 56 | /// The name of the city based on the locales list passed to the 57 | /// constructor. Don't use any of 58 | /// these names as a database or dictionary key. Use the 59 | /// 61 | /// or relevant code instead. 62 | /// 63 | [JsonIgnore] 64 | public string? Name 65 | { 66 | get 67 | { 68 | var locale = Locales.FirstOrDefault(l => Names.ContainsKey(l)); 69 | return locale == null ? null : Names[locale]; 70 | } 71 | } 72 | 73 | /// 74 | /// Returns a that represents this instance. 75 | /// 76 | /// 77 | /// A that represents this instance. 78 | /// 79 | public override string ToString() 80 | { 81 | return Name ?? string.Empty; 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/Postal.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Text.Json.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Model 9 | { 10 | /// 11 | /// Contains data for the postal record associated with an IP address. 12 | /// 13 | public class Postal 14 | { 15 | /// 16 | /// Constructor 17 | /// 18 | public Postal() 19 | { 20 | } 21 | 22 | /// 23 | /// Constructor 24 | /// 25 | [Constructor] 26 | public Postal(string? code = null, int? confidence = null) 27 | { 28 | Code = code; 29 | Confidence = confidence; 30 | } 31 | 32 | /// 33 | /// The postal code of the location. Postal codes are not available 34 | /// for all countries. In some countries, this will only contain part 35 | /// of the postal code. 36 | /// 37 | [JsonInclude] 38 | [JsonPropertyName("code")] 39 | public string? Code { get; internal set; } 40 | 41 | /// 42 | /// A value from 0-100 indicating MaxMind's confidence that the 43 | /// postal code is correct. This value is only set when using the 44 | /// Insights web service or the Enterprise database. 45 | /// 46 | [JsonInclude] 47 | [JsonPropertyName("confidence")] 48 | public int? Confidence { get; internal set; } 49 | 50 | /// 51 | /// Returns a that represents this instance. 52 | /// 53 | /// 54 | /// A that represents this instance. 55 | /// 56 | public override string ToString() 57 | { 58 | return $"Code: {Code}, Confidence: {Confidence}"; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/RepresentedCountry.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Collections.Generic; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Model 10 | { 11 | /// 12 | /// Contains data for the represented country associated with an IP address. 13 | /// This class contains the country-level data associated with an IP address for 14 | /// the IP's represented country. The represented country is the country 15 | /// represented by something like a military base. 16 | /// Do not use any of the country names as a database or dictionary 17 | /// key. Use the or 18 | /// instead. 19 | /// 20 | public class RepresentedCountry : Country 21 | { 22 | /// 23 | /// Constructor 24 | /// 25 | public RepresentedCountry() 26 | { 27 | } 28 | 29 | /// 30 | /// Constructor 31 | /// 32 | [Constructor] 33 | public RepresentedCountry( 34 | string? type = null, 35 | int? confidence = null, 36 | [Parameter("geoname_id")] long? geoNameId = null, 37 | [Parameter("is_in_european_union")] bool isInEuropeanUnion = false, 38 | [Parameter("iso_code")] string? isoCode = null, 39 | IReadOnlyDictionary? names = null, 40 | IReadOnlyList? locales = null) 41 | : base(confidence, geoNameId, isInEuropeanUnion, isoCode, names, locales) 42 | { 43 | Type = type; 44 | } 45 | 46 | /// 47 | /// A string indicating the type of entity that is representing the 48 | /// country. Currently we only return military but this could 49 | /// expand to include other types in the future. 50 | /// 51 | [JsonInclude] 52 | [JsonPropertyName("type")] 53 | public string? Type { get; internal set; } 54 | } 55 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/Subdivision.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Collections.Generic; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Model 10 | { 11 | /// 12 | /// Contains data for the subdivisions associated with an IP address. 13 | /// Do not use any of the subdivision names as a database or dictionary 14 | /// key. Use the or 15 | /// instead. 16 | /// 17 | public class Subdivision : NamedEntity 18 | { 19 | /// 20 | /// Constructor 21 | /// 22 | public Subdivision() 23 | { 24 | } 25 | 26 | /// 27 | /// Constructor 28 | /// 29 | [Constructor] 30 | public Subdivision( 31 | int? confidence = null, 32 | [Parameter("geoname_id")] long? geoNameId = null, 33 | [Parameter("iso_code")] string? isoCode = null, 34 | IReadOnlyDictionary? names = null, 35 | IReadOnlyList? locales = null) 36 | : base(geoNameId, names, locales) 37 | { 38 | Confidence = confidence; 39 | IsoCode = isoCode; 40 | } 41 | 42 | /// 43 | /// This is a value from 0-100 indicating MaxMind's confidence that 44 | /// the subdivision is correct. This value is only set when using the 45 | /// Insights web service or the Enterprise database. 46 | /// 47 | [JsonInclude] 48 | [JsonPropertyName("confidence")] 49 | public int? Confidence { get; internal set; } 50 | 51 | /// 52 | /// This is a string up to three characters long contain the 53 | /// subdivision portion of the 54 | /// 56 | /// ISO 3166-2 code 57 | /// 58 | /// . 59 | /// 60 | [JsonInclude] 61 | [JsonPropertyName("iso_code")] 62 | public string? IsoCode { get; internal set; } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Model/WebServiceError.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace MaxMind.GeoIP2.Model 4 | { 5 | /// 6 | /// Contains data about an error that occurred while calling the web service 7 | /// 8 | internal class WebServiceError 9 | { 10 | /// 11 | /// Gets or sets the error. 12 | /// 13 | /// 14 | /// The error message returned by the service. 15 | /// 16 | [JsonPropertyName("error")] 17 | public string? Error { get; set; } 18 | 19 | /// 20 | /// Gets or sets the code. 21 | /// 22 | /// 23 | /// The error code returned by the service. 24 | /// 25 | [JsonPropertyName("code")] 26 | public string? Code { get; set; } 27 | } 28 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/NetworkConverter.cs: -------------------------------------------------------------------------------- 1 | using MaxMind.Db; 2 | using System; 3 | using System.Net; 4 | using System.Text.Json; 5 | using System.Text.Json.Serialization; 6 | 7 | namespace MaxMind.GeoIP2 8 | { 9 | internal class NetworkConverter : JsonConverter 10 | { 11 | public override void Write(Utf8JsonWriter writer, Network? value, JsonSerializerOptions options) 12 | { 13 | writer.WriteStringValue(value?.ToString()); 14 | } 15 | 16 | public override Network? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 17 | { 18 | var value = reader.GetString(); 19 | if (value == null) 20 | { 21 | return null; 22 | } 23 | // It'd probably be nice if we added an appropriate constructor 24 | // to Network. 25 | var parts = value.Split('/'); 26 | if (parts.Length != 2 || !int.TryParse(parts[1], out var prefixLength)) 27 | { 28 | throw new JsonException("Network not in CIDR format: " + value); 29 | } 30 | 31 | return new Network(IPAddress.Parse(parts[0]), prefixLength); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | 6 | 7 | false 8 | 9 | 10 | false 11 | 12 | 13 | true 14 | 15 | 16 | false 17 | 18 | 19 | 20 | 21 | 22 | 26 | 27 | 28 | 29 | 30 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 31 | $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) 32 | 33 | 34 | 35 | 36 | $(SolutionDir).nuget 37 | packages.config 38 | 39 | 40 | 41 | 42 | $(NuGetToolsPath)\NuGet.exe 43 | @(PackageSource) 44 | 45 | "$(NuGetExePath)" 46 | mono --runtime=v4.0.30319 $(NuGetExePath) 47 | 48 | $(TargetDir.Trim('\\')) 49 | 50 | -RequireConsent 51 | -NonInteractive 52 | 53 | "$(SolutionDir) " 54 | "$(SolutionDir)" 55 | 56 | 57 | $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) 58 | $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols 59 | 60 | 61 | 62 | RestorePackages; 63 | $(BuildDependsOn); 64 | 65 | 66 | 67 | 68 | $(BuildDependsOn); 69 | BuildPackage; 70 | 71 | 72 | 73 | 74 | 75 | 76 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 91 | 92 | 95 | 96 | 97 | 98 | 100 | 101 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System; 4 | using System.Reflection; 5 | using System.Runtime.CompilerServices; 6 | using System.Runtime.InteropServices; 7 | 8 | #endregion 9 | 10 | // General Information about an assembly is controlled through the following 11 | // set of attributes. Change these attribute values to modify the information 12 | // associated with an assembly. 13 | 14 | [assembly: AssemblyTitle("MaxMind.GeoIP2")] 15 | [assembly: AssemblyDescription("MaxMind GeoIP2 Database Reader and Web Service Client")] 16 | [assembly: AssemblyConfiguration("")] 17 | [assembly: AssemblyCompany("MaxMind, Inc.")] 18 | [assembly: AssemblyProduct("MaxMind.GeoIP2")] 19 | [assembly: AssemblyCopyright("Copyright © 2013-2025")] 20 | [assembly: AssemblyTrademark("")] 21 | [assembly: AssemblyCulture("")] 22 | 23 | // Setting ComVisible to false makes the types in this assembly not visible 24 | // to COM components. If you need to access a type in this assembly from 25 | // COM, set the ComVisible attribute to true on that type. 26 | 27 | [assembly: ComVisible(false)] 28 | 29 | // The following GUID is for the ID of the typelib if this project is exposed to COM 30 | 31 | [assembly: Guid("7352289c-bf62-4994-bc2b-6cf4c1ea4b2d")] 32 | [assembly: CLSCompliant(true)] 33 | 34 | // Version information for an assembly consists of the following four values: 35 | // 36 | // Major Version 37 | // Minor Version 38 | // Build Number 39 | // Revision 40 | // 41 | // You can specify all the values or you can default the Build and Revision Numbers 42 | // by using the '*' as shown below: 43 | // [assembly: AssemblyVersion("1.0.*")] 44 | 45 | [assembly: AssemblyVersion("4.0.0.0")] 46 | [assembly: AssemblyFileVersion("4.0.0")] 47 | [assembly: AssemblyInformationalVersion("4.0.0")] 48 | [assembly: InternalsVisibleTo("MaxMind.GeoIP2.UnitTests,PublicKey=" + 49 | "0024000004800000940000000602000000240000525341310004000001000100e30b6e4a9425b1" + 50 | "617ffc8bdf79801e67a371f9f650db860dc0dfff92cb63258765a0955c6fcde1da78dbaf5bf84d" + 51 | "0230946435957d2e52dc0d15673e372248dbff3bc8e6c75a632072e52cb0444850dddff5cc2be8" + 52 | "f3e1f8954d7ede7675675a071672d9e97d3153d96b40fd30234be33eeb7fd1a4a78d6342967700" + 53 | "56a2b1e5")] 54 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/AbstractCityResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Model; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text.Json.Serialization; 7 | 8 | #endregion 9 | 10 | namespace MaxMind.GeoIP2.Responses 11 | { 12 | /// 13 | /// Abstract class that city-level response. 14 | /// 15 | public abstract class AbstractCityResponse : AbstractCountryResponse 16 | { 17 | /// 18 | /// Initializes a new instance of the class. 19 | /// 20 | protected AbstractCityResponse() 21 | { 22 | City = new City(); 23 | Location = new Location(); 24 | Postal = new Postal(); 25 | Subdivisions = new List().AsReadOnly(); 26 | } 27 | 28 | /// 29 | /// Initializes a new instance of the class. 30 | /// 31 | protected AbstractCityResponse( 32 | City? city = null, 33 | Continent? continent = null, 34 | Country? country = null, 35 | Location? location = null, 36 | Model.MaxMind? maxMind = null, 37 | Postal? postal = null, 38 | Country? registeredCountry = null, 39 | RepresentedCountry? representedCountry = null, 40 | IReadOnlyList? subdivisions = null, 41 | Traits? traits = null) 42 | : base(continent, country, maxMind, registeredCountry, representedCountry, traits) 43 | { 44 | City = city ?? new City(); 45 | Location = location ?? new Location(); 46 | Postal = postal ?? new Postal(); 47 | Subdivisions = subdivisions ?? new List().AsReadOnly(); 48 | } 49 | 50 | /// 51 | /// Gets the city for the requested IP address. 52 | /// 53 | [JsonInclude] 54 | [JsonPropertyName("city")] 55 | public City City { get; internal set; } 56 | 57 | /// 58 | /// Gets the location for the requested IP address. 59 | /// 60 | [JsonInclude] 61 | [JsonPropertyName("location")] 62 | public Location Location { get; internal set; } 63 | 64 | /// 65 | /// Gets the postal object for the requested IP address. 66 | /// 67 | [JsonInclude] 68 | [JsonPropertyName("postal")] 69 | public Postal Postal { get; internal set; } 70 | 71 | /// 72 | /// An of objects representing 73 | /// the country subdivisions for the requested IP address. The number 74 | /// and type of subdivisions varies by country, but a subdivision is 75 | /// typically a state, province, county, etc. Subdivisions are 76 | /// ordered from most general (largest) to most specific (smallest). 77 | /// If the response did not contain any subdivisions, this method 78 | /// returns an empty array. 79 | /// 80 | [JsonInclude] 81 | [JsonPropertyName("subdivisions")] 82 | public IReadOnlyList Subdivisions { get; internal set; } 83 | 84 | /// 85 | /// An object representing the most specific subdivision returned. If 86 | /// the response did not contain any subdivisions, this method 87 | /// returns an empty object. 88 | /// 89 | [JsonIgnore] 90 | public Subdivision MostSpecificSubdivision => Subdivisions.Count == 0 ? new Subdivision() : Subdivisions[Subdivisions.Count - 1]; 91 | 92 | /// 93 | /// Returns a that represents this instance. 94 | /// 95 | /// 96 | /// A that represents this instance. 97 | /// 98 | public override string ToString() 99 | { 100 | return GetType().Name + " [" 101 | + "City=" + City + ", " 102 | + "Location=" + Location + ", " 103 | + "Postal=" + Postal + ", " 104 | + "Subdivisions={" + 105 | string.Join(",", Subdivisions.Select(s => s.ToString()).ToArray()) + "}, " 106 | + "Continent=" + Continent + ", " 107 | + "Country=" + Country + ", " 108 | + "RegisteredCountry=" + RegisteredCountry + ", " 109 | + "RepresentedCountry=" + RepresentedCountry + ", " 110 | + "Traits=" + Traits 111 | + "]"; 112 | } 113 | 114 | /// 115 | /// Sets the locales on all the NamedEntity properties. 116 | /// 117 | /// The locales specified by the user. 118 | protected internal override void SetLocales(IReadOnlyList locales) 119 | { 120 | locales = [.. locales]; 121 | base.SetLocales(locales); 122 | City.Locales = locales; 123 | 124 | if (Subdivisions.Count == 0) 125 | { 126 | return; 127 | } 128 | 129 | foreach (var subdivision in Subdivisions) 130 | { 131 | subdivision.Locales = locales; 132 | } 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/AbstractCountryResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Model; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text.Json.Serialization; 7 | 8 | #endregion 9 | 10 | namespace MaxMind.GeoIP2.Responses 11 | { 12 | /// 13 | /// Abstract class for country-level response. 14 | /// 15 | public abstract class AbstractCountryResponse : AbstractResponse 16 | { 17 | /// 18 | /// Initializes a new instance of the class. 19 | /// 20 | protected AbstractCountryResponse() 21 | { 22 | Continent = new Continent(); 23 | Country = new Country(); 24 | MaxMind = new Model.MaxMind(); 25 | RegisteredCountry = new Country(); 26 | RepresentedCountry = new RepresentedCountry(); 27 | Traits = new Traits(); 28 | } 29 | 30 | /// 31 | /// Initializes a new instance of the class. 32 | /// 33 | protected AbstractCountryResponse( 34 | Continent? continent = null, 35 | Country? country = null, 36 | Model.MaxMind? maxMind = null, 37 | Country? registeredCountry = null, 38 | RepresentedCountry? representedCountry = null, 39 | Traits? traits = null) 40 | { 41 | Continent = continent ?? new Continent(); 42 | Country = country ?? new Country(); 43 | MaxMind = maxMind ?? new Model.MaxMind(); 44 | RegisteredCountry = registeredCountry ?? new Country(); 45 | RepresentedCountry = representedCountry ?? new RepresentedCountry(); 46 | Traits = traits ?? new Traits(); 47 | } 48 | 49 | /// 50 | /// Gets the continent for the requested IP address. 51 | /// 52 | [JsonInclude] 53 | [JsonPropertyName("continent")] 54 | public Continent Continent { get; internal set; } 55 | 56 | /// 57 | /// Gets the country for the requested IP address. This 58 | /// object represents the country where MaxMind believes 59 | /// the end user is located 60 | /// 61 | [JsonInclude] 62 | [JsonPropertyName("country")] 63 | public Country Country { get; internal set; } 64 | 65 | /// 66 | /// Gets the MaxMind record containing data related to your account 67 | /// 68 | [JsonInclude] 69 | [JsonPropertyName("maxmind")] 70 | public Model.MaxMind MaxMind { get; internal set; } 71 | 72 | /// 73 | /// Registered country record for the requested IP address. This 74 | /// record represents the country where the ISP has registered a 75 | /// given IP block and may differ from the user's country. 76 | /// 77 | [JsonInclude] 78 | [JsonPropertyName("registered_country")] 79 | public Country RegisteredCountry { get; internal set; } 80 | 81 | /// 82 | /// Represented country record for the requested IP address. The 83 | /// represented country is used for things like military bases or 84 | /// embassies. It is only present when the represented country 85 | /// differs from the country. 86 | /// 87 | [JsonInclude] 88 | [JsonPropertyName("represented_country")] 89 | public RepresentedCountry RepresentedCountry { get; internal set; } 90 | 91 | /// 92 | /// Gets the traits for the requested IP address. 93 | /// 94 | [JsonInclude] 95 | [JsonPropertyName("traits")] 96 | public Traits Traits { get; internal set; } 97 | 98 | /// 99 | /// Returns a that represents this instance. 100 | /// 101 | /// 102 | /// A that represents this instance. 103 | /// 104 | public override string ToString() 105 | { 106 | return GetType().Name + " [" 107 | + "Continent=" + Continent + ", " 108 | + "Country=" + Country + ", " 109 | + "RegisteredCountry=" + RegisteredCountry + ", " 110 | + "RepresentedCountry=" + RepresentedCountry + ", " 111 | + "Traits=" + Traits 112 | + "]"; 113 | } 114 | 115 | /// 116 | /// Sets the locales on all the NamedEntity properties. 117 | /// 118 | /// The locales specified by the user. 119 | protected internal override void SetLocales(IReadOnlyList locales) 120 | { 121 | locales = [.. locales]; 122 | Continent.Locales = locales; 123 | Country.Locales = locales; 124 | RegisteredCountry.Locales = locales; 125 | RepresentedCountry.Locales = locales; 126 | } 127 | } 128 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/AbstractResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using System.Collections.Generic; 4 | 5 | #endregion 6 | 7 | namespace MaxMind.GeoIP2.Responses 8 | { 9 | /// 10 | /// Abstract class that represents a generic response. 11 | /// 12 | public abstract class AbstractResponse 13 | { 14 | /// 15 | /// This is simplify the database API. Also, we may need to use the locales in the future. 16 | /// 17 | /// 18 | protected internal virtual void SetLocales(IReadOnlyList locales) 19 | { 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/AnonymousIPResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Text.Json.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Responses 9 | { 10 | /// 11 | /// This class represents the GeoIP2 Anonymous IP response. 12 | /// 13 | public class AnonymousIPResponse : AbstractResponse 14 | { 15 | /// 16 | /// Construct AnonymousIPResponse model 17 | /// 18 | public AnonymousIPResponse() 19 | { 20 | } 21 | 22 | /// 23 | /// Construct AnonymousIPResponse model 24 | /// 25 | /// 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// 32 | /// 33 | [Constructor] 34 | public AnonymousIPResponse( 35 | [Parameter("is_anonymous")] bool isAnonymous, 36 | [Parameter("is_anonymous_vpn")] bool isAnonymousVpn, 37 | [Parameter("is_hosting_provider")] bool isHostingProvider, 38 | [Parameter("is_public_proxy")] bool isPublicProxy, 39 | [Parameter("is_residential_proxy")] bool isResidentialProxy, 40 | [Parameter("is_tor_exit_node")] bool isTorExitNode, 41 | [Inject("ip_address")] string? ipAddress, 42 | [Network] Network? network = null 43 | ) 44 | { 45 | IsAnonymous = isAnonymous; 46 | IsAnonymousVpn = isAnonymousVpn; 47 | IsHostingProvider = isHostingProvider; 48 | IsPublicProxy = isPublicProxy; 49 | IsResidentialProxy = isResidentialProxy; 50 | IsTorExitNode = isTorExitNode; 51 | IPAddress = ipAddress; 52 | Network = network; 53 | } 54 | 55 | /// 56 | /// Returns true if the IP address belongs to any sort of anonymous network. 57 | /// 58 | [JsonInclude] 59 | [JsonPropertyName("is_anonymous")] 60 | public bool IsAnonymous { get; internal set; } 61 | 62 | /// 63 | /// Returns true if the IP address is registered to an anonymous 64 | /// VPN provider. 65 | /// 66 | /// 67 | /// If a VPN provider does not register subnets under names 68 | /// associated with them, we will likely only flag their IP ranges 69 | /// using the IsHostingProvider property. 70 | /// 71 | [JsonInclude] 72 | [JsonPropertyName("is_anonymous_vpn")] 73 | public bool IsAnonymousVpn { get; internal set; } 74 | 75 | /// 76 | /// Returns true if the IP address belongs to a hosting or 77 | /// VPN provider (see description of IsAnonymousVpn property). 78 | /// 79 | [JsonInclude] 80 | [JsonPropertyName("is_hosting_provider")] 81 | public bool IsHostingProvider { get; internal set; } 82 | 83 | /// 84 | /// Returns true if the IP address belongs to a public proxy. 85 | /// 86 | [JsonInclude] 87 | [JsonPropertyName("is_public_proxy")] 88 | public bool IsPublicProxy { get; internal set; } 89 | 90 | /// 91 | /// This is true if the IP address is on a suspected anonymizing 92 | /// network and belongs to a residential ISP. 93 | /// 94 | [JsonInclude] 95 | [JsonPropertyName("is_residential_proxy")] 96 | public bool IsResidentialProxy { get; internal set; } 97 | 98 | /// 99 | /// Returns true if IP is a Tor exit node. 100 | /// 101 | [JsonInclude] 102 | [JsonPropertyName("is_tor_exit_node")] 103 | public bool IsTorExitNode { get; internal set; } 104 | 105 | /// 106 | /// The IP address that the data in the model is for. If you 107 | /// performed a "me" lookup against the web service, this will be the 108 | /// externally routable IP address for the system the code is running 109 | /// on. If the system is behind a NAT, this may differ from the IP 110 | /// address locally assigned to it. 111 | /// 112 | [JsonInclude] 113 | [JsonPropertyName("ip_address")] 114 | public string? IPAddress { get; internal set; } 115 | 116 | /// 117 | /// The network associated with the record. In particular, this is 118 | /// the largest network where all of the fields besides 119 | /// IPAddress have the same value. 120 | /// 121 | [JsonInclude] 122 | [JsonPropertyName("network")] 123 | public Network? Network { get; internal set; } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/AnonymousPlusResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System; 5 | using System.Text.Json.Serialization; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Responses 10 | { 11 | /// 12 | /// This class represents the GeoIP Anonymous Plus response. 13 | /// 14 | public class AnonymousPlusResponse : AnonymousIPResponse 15 | { 16 | /// 17 | /// Construct AnonymousPlusResponse model 18 | /// 19 | public AnonymousPlusResponse() 20 | { 21 | } 22 | 23 | #if NET6_0_OR_GREATER 24 | /// 25 | /// Construct AnonymousPlusResponse model 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// 31 | /// 32 | /// 33 | /// 34 | /// 35 | /// 36 | /// 37 | /// 38 | [Constructor] 39 | public AnonymousPlusResponse( 40 | [Parameter("anonymizer_confidence")] int? anonymizerConfidence, 41 | [Parameter("is_anonymous")] bool isAnonymous, 42 | [Parameter("is_anonymous_vpn")] bool isAnonymousVpn, 43 | [Parameter("is_hosting_provider")] bool isHostingProvider, 44 | [Parameter("is_public_proxy")] bool isPublicProxy, 45 | [Parameter("is_residential_proxy")] bool isResidentialProxy, 46 | [Parameter("is_tor_exit_node")] bool isTorExitNode, 47 | [Inject("ip_address")] string? ipAddress, 48 | [Network] Network? network = null, 49 | [Parameter("network_last_seen")] string? networkLastSeen = null, 50 | [Parameter("provider_name")] string? providerName = null 51 | ) : this(anonymizerConfidence, isAnonymous, isAnonymousVpn, isHostingProvider, isPublicProxy, 52 | isResidentialProxy, isTorExitNode, ipAddress, network, 53 | networkLastSeen == null ? null : DateOnly.Parse(networkLastSeen), 54 | providerName 55 | ) 56 | { } 57 | 58 | /// 59 | /// Construct AnonymousPlusResponse model 60 | /// 61 | /// 62 | /// 63 | /// 64 | /// 65 | /// 66 | /// 67 | /// 68 | /// 69 | /// 70 | /// 71 | /// 72 | public AnonymousPlusResponse( 73 | int? anonymizerConfidence, 74 | bool isAnonymous, 75 | bool isAnonymousVpn, 76 | bool isHostingProvider, 77 | bool isPublicProxy, 78 | bool isResidentialProxy, 79 | bool isTorExitNode, 80 | string? ipAddress, 81 | Network? network = null, 82 | DateOnly? networkLastSeen = null, 83 | string? providerName = null 84 | ) : base(isAnonymous, isAnonymousVpn, isHostingProvider, isPublicProxy, 85 | isResidentialProxy, isTorExitNode, ipAddress, network) 86 | { 87 | AnonymizerConfidence = anonymizerConfidence; 88 | NetworkLastSeen = networkLastSeen; 89 | ProviderName = providerName; 90 | } 91 | #else 92 | /// 93 | /// Construct AnonymousPlusResponse model 94 | /// 95 | /// 96 | /// 97 | /// 98 | /// 99 | /// 100 | /// 101 | /// 102 | /// 103 | /// 104 | /// 105 | [Constructor] 106 | public AnonymousPlusResponse( 107 | [Parameter("anonymizer_confidence")] int anonymizerConfidence, 108 | [Parameter("is_anonymous")] bool isAnonymous, 109 | [Parameter("is_anonymous_vpn")] bool isAnonymousVpn, 110 | [Parameter("is_hosting_provider")] bool isHostingProvider, 111 | [Parameter("is_public_proxy")] bool isPublicProxy, 112 | [Parameter("is_residential_proxy")] bool isResidentialProxy, 113 | [Parameter("is_tor_exit_node")] bool isTorExitNode, 114 | [Inject("ip_address")] string? ipAddress, 115 | [Network] Network? network = null, 116 | [Parameter("provider_name")] string? providerName = null 117 | ) : base(isAnonymous, isAnonymousVpn, isHostingProvider, isPublicProxy, 118 | isResidentialProxy, isTorExitNode, ipAddress, network) 119 | { 120 | AnonymizerConfidence = anonymizerConfidence; 121 | ProviderName = providerName; 122 | } 123 | #endif 124 | 125 | /// 126 | /// A score ranging from 1 to 99 that is our percent confidence 127 | /// that the network is currently part of an actively used VPN 128 | /// service. 129 | /// 130 | [JsonInclude] 131 | [JsonPropertyName("anonymizer_confidence")] 132 | public int? AnonymizerConfidence { get; internal set; } 133 | 134 | #if NET6_0_OR_GREATER 135 | /// 136 | /// The last day that the network was sighted in our analysis of 137 | /// anonymized networks. 138 | /// 139 | [JsonInclude] 140 | [JsonPropertyName("network_last_seen")] 141 | public DateOnly? NetworkLastSeen { get; internal set; } 142 | #endif 143 | 144 | /// 145 | /// The name of the VPN provider (e.g., NordVPN, SurfShark, etc.) 146 | /// associated with the network. 147 | /// 148 | [JsonInclude] 149 | [JsonPropertyName("provider_name")] 150 | public string? ProviderName { get; internal set; } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/AsnResponse.cs: -------------------------------------------------------------------------------- 1 | using MaxMind.Db; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace MaxMind.GeoIP2.Responses 5 | { 6 | /// 7 | /// This class represents the GeoLite2 ASN response. 8 | /// 9 | /// 10 | /// Construct an AsnResponse model. 11 | /// 12 | [method: Constructor] 13 | public class AsnResponse( 14 | [Parameter("autonomous_system_number")] long? autonomousSystemNumber, 15 | [Parameter("autonomous_system_organization")] string? autonomousSystemOrganization, 16 | [Inject("ip_address")] string? ipAddress, 17 | [Network] Network? network = null 18 | ) : AbstractResponse 19 | { 20 | /// 21 | /// Construct an AsnResponse model. 22 | /// 23 | public AsnResponse() : this(null, null, null) 24 | { 25 | } 26 | 27 | /// 28 | /// The 29 | /// 31 | /// autonomous system number 32 | /// 33 | /// associated with the IP address. 34 | /// 35 | [JsonInclude] 36 | [JsonPropertyName("autonomous_system_number")] 37 | public long? AutonomousSystemNumber { get; internal set; } = autonomousSystemNumber; 38 | 39 | /// 40 | /// The organization associated with the registered 41 | /// 43 | /// autonomous system number 44 | /// 45 | /// for the IP address. 46 | /// 47 | [JsonInclude] 48 | [JsonPropertyName("autonomous_system_organization")] 49 | public string? AutonomousSystemOrganization { get; internal set; } = autonomousSystemOrganization; 50 | 51 | /// 52 | /// The IP address that the data in the model is for. If you 53 | /// performed a "me" lookup against the web service, this will be the 54 | /// externally routable IP address for the system the code is running 55 | /// on. If the system is behind a NAT, this may differ from the IP 56 | /// address locally assigned to it. 57 | /// 58 | [JsonInclude] 59 | [JsonPropertyName("ip_address")] 60 | public string? IPAddress { get; internal set; } = ipAddress; 61 | 62 | /// 63 | /// The network associated with the record. In particular, this is 64 | /// the largest network where all of the fields besides 65 | /// IPAddress have the same value. 66 | /// 67 | [JsonInclude] 68 | [JsonPropertyName("network")] 69 | public Network? Network { get; internal set; } = network; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/CityResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using MaxMind.GeoIP2.Model; 5 | using System.Collections.Generic; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Responses 10 | { 11 | /// 12 | /// This class provides a model for data returned from the GeoIP2 City 13 | /// database and the GeoIP2 City Plus web services. 14 | /// 15 | public class CityResponse : AbstractCityResponse 16 | { 17 | /// 18 | /// Constructor 19 | /// 20 | public CityResponse() 21 | { 22 | } 23 | 24 | /// 25 | /// Constructor 26 | /// 27 | [Constructor] 28 | public CityResponse( 29 | City? city = null, 30 | Continent? continent = null, 31 | Country? country = null, 32 | Location? location = null, 33 | [Parameter("maxmind")] Model.MaxMind? maxMind = null, 34 | Postal? postal = null, 35 | [Parameter("registered_country")] Country? registeredCountry = null, 36 | [Parameter("represented_country")] RepresentedCountry? representedCountry = null, 37 | IReadOnlyList? subdivisions = null, 38 | [Parameter("traits", true)] Traits? traits = null) 39 | : base( 40 | city, continent, country, location, maxMind, postal, registeredCountry, representedCountry, subdivisions, 41 | traits) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/ConnectionTypeResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Text.Json.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Responses 9 | { 10 | /// 11 | /// This class represents the GeoIP2 Connection-Type response. 12 | /// 13 | public class ConnectionTypeResponse : AbstractResponse 14 | { 15 | /// 16 | /// Construct ConnectionTypeResponse model 17 | /// 18 | public ConnectionTypeResponse() 19 | { 20 | } 21 | 22 | /// 23 | /// Construct ConnectionTypeResponse model 24 | /// 25 | [Constructor] 26 | public ConnectionTypeResponse( 27 | [Parameter("connection_type")] string? connectionType, 28 | [Inject("ip_address")] string? ipAddress, 29 | [Network] Network? network = null 30 | ) 31 | { 32 | ConnectionType = connectionType; 33 | IPAddress = ipAddress; 34 | Network = network; 35 | } 36 | 37 | /// 38 | /// The connection type may take the following values: "Dialup", 39 | /// "Cable/DSL", "Corporate", "Cellular", and "Satellite". Additional 40 | /// values may be added in the future. 41 | /// 42 | [JsonInclude] 43 | [JsonPropertyName("connection_type")] 44 | public string? ConnectionType { get; internal set; } 45 | 46 | /// 47 | /// The IP address that the data in the model is for. If you 48 | /// performed a "me" lookup against the web service, this will be the 49 | /// externally routable IP address for the system the code is running 50 | /// on. If the system is behind a NAT, this may differ from the IP 51 | /// address locally assigned to it. 52 | /// 53 | [JsonInclude] 54 | [JsonPropertyName("ip_address")] 55 | public string? IPAddress { get; internal set; } 56 | 57 | /// 58 | /// The network associated with the record. In particular, this is 59 | /// the largest network where all of the fields besides 60 | /// IPAddress have the same value. 61 | /// 62 | [JsonInclude] 63 | [JsonPropertyName("network")] 64 | public Network? Network { get; internal set; } 65 | } 66 | } -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/CountryResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using MaxMind.GeoIP2.Model; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Responses 9 | { 10 | /// 11 | /// This class provides a model for the data returned from the GeoIP2 12 | /// Country database and the GeoIP2 Country web service. 13 | /// 14 | public class CountryResponse : AbstractCountryResponse 15 | { 16 | /// 17 | /// Constructor 18 | /// 19 | public CountryResponse() 20 | { 21 | } 22 | 23 | /// 24 | /// Constructor 25 | /// 26 | [Constructor] 27 | public CountryResponse( 28 | Continent? continent = null, 29 | Country? country = null, 30 | [Parameter("maxmind")] Model.MaxMind? maxMind = null, 31 | [Parameter("registered_country")] Country? registeredCountry = null, 32 | [Parameter("represented_country")] RepresentedCountry? representedCountry = null, 33 | [Parameter("traits", true)] Traits? traits = null 34 | ) : base(continent, country, maxMind, registeredCountry, representedCountry, traits) 35 | { 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/DomainResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Text.Json.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Responses 9 | { 10 | /// 11 | /// This class represents the GeoIP2 Domain response. 12 | /// 13 | /// 14 | /// Construct a DomainResponse model object. 15 | /// 16 | /// 17 | /// 18 | /// 19 | [method: Constructor] 20 | public class DomainResponse( 21 | string? domain, 22 | [Inject("ip_address")] string? ipAddress, 23 | [Network] Network? network = null 24 | ) : AbstractResponse 25 | { 26 | /// 27 | /// Construct a DomainResponse model object. 28 | /// 29 | public DomainResponse() : this(null, null) 30 | { 31 | } 32 | 33 | /// 34 | /// The second level domain associated with the IP address. This will 35 | /// be something like "example.com" or "example.co.uk", not 36 | /// "foo.example.com". 37 | /// 38 | [JsonInclude] 39 | [JsonPropertyName("domain")] 40 | public string? Domain { get; internal set; } = domain; 41 | 42 | /// 43 | /// The IP address that the data in the model is for. If you 44 | /// performed a "me" lookup against the web service, this will be the 45 | /// externally routable IP address for the system the code is running 46 | /// on. If the system is behind a NAT, this may differ from the IP 47 | /// address locally assigned to it. 48 | /// 49 | [JsonInclude] 50 | [JsonPropertyName("ip_address")] 51 | public string? IPAddress { get; internal set; } = ipAddress; 52 | 53 | /// 54 | /// The network associated with the record. In particular, this is 55 | /// the largest network where all of the fields besides 56 | /// IPAddress have the same value. 57 | /// 58 | [JsonInclude] 59 | [JsonPropertyName("network")] 60 | public Network? Network { get; internal set; } = network; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/EnterpriseResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using MaxMind.GeoIP2.Model; 5 | using System.Collections.Generic; 6 | 7 | #endregion 8 | 9 | namespace MaxMind.GeoIP2.Responses 10 | { 11 | /// 12 | /// This class provides a model for the data returned by the GeoIP2 Enterprise 13 | /// database. 14 | /// 15 | /// 16 | /// Constructor 17 | /// 18 | [method: Constructor] 19 | public class EnterpriseResponse( 20 | City? city = null, 21 | Continent? continent = null, 22 | Country? country = null, 23 | Location? location = null, 24 | Model.MaxMind? maxMind = null, 25 | Postal? postal = null, 26 | Country? registeredCountry = null, 27 | RepresentedCountry? representedCountry = null, 28 | IReadOnlyList? subdivisions = null, 29 | Traits? traits = null) : AbstractCityResponse( 30 | city, continent, country, location, maxMind, postal, registeredCountry, representedCountry, subdivisions, 31 | traits) 32 | { 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/InsightsResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.GeoIP2.Model; 4 | using System.Collections.Generic; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Responses 9 | { 10 | /// 11 | /// This class provides a model for the data returned by the GeoIP2 12 | /// Insights web service. 13 | /// 14 | public class InsightsResponse : AbstractCityResponse 15 | { 16 | /// 17 | /// Constructor 18 | /// 19 | public InsightsResponse() 20 | { 21 | } 22 | 23 | /// 24 | /// Constructor 25 | /// 26 | public InsightsResponse( 27 | City? city = null, 28 | Continent? continent = null, 29 | Country? country = null, 30 | Location? location = null, 31 | Model.MaxMind? maxMind = null, 32 | Postal? postal = null, 33 | Country? registeredCountry = null, 34 | RepresentedCountry? representedCountry = null, 35 | IReadOnlyList? subdivisions = null, 36 | Traits? traits = null) 37 | : base( 38 | city, continent, country, location, maxMind, postal, registeredCountry, representedCountry, subdivisions, 39 | traits) 40 | { 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/Responses/IspResponse.cs: -------------------------------------------------------------------------------- 1 | #region 2 | 3 | using MaxMind.Db; 4 | using System.Text.Json.Serialization; 5 | 6 | #endregion 7 | 8 | namespace MaxMind.GeoIP2.Responses 9 | { 10 | /// 11 | /// This class represents the GeoIP2 ISP response. 12 | /// 13 | /// 14 | /// Construct an IspResponse model. 15 | /// 16 | [method: Constructor] 17 | public class IspResponse( 18 | [Parameter("autonomous_system_number")] long? autonomousSystemNumber, 19 | [Parameter("autonomous_system_organization")] string? autonomousSystemOrganization, 20 | string? isp, 21 | [Parameter("mobile_country_code")] string? mobileCountryCode, 22 | [Parameter("mobile_network_code")] string? mobileNetworkCode, 23 | string? organization, 24 | [Inject("ip_address")] string? ipAddress, 25 | [Network] Network? network = null 26 | ) : AbstractResponse 27 | { 28 | /// 29 | /// Construct an IspResponse model. 30 | /// 31 | public IspResponse() : this(null, null, null, null, null, null, null) 32 | { 33 | } 34 | 35 | /// 36 | /// The 37 | /// 39 | /// autonomous system number 40 | /// 41 | /// associated with the IP address. 42 | /// 43 | [JsonInclude] 44 | [JsonPropertyName("autonomous_system_number")] 45 | public long? AutonomousSystemNumber { get; internal set; } = autonomousSystemNumber; 46 | 47 | /// 48 | /// The organization associated with the registered 49 | /// 51 | /// autonomous system number 52 | /// 53 | /// for the IP address. 54 | /// 55 | [JsonInclude] 56 | [JsonPropertyName("autonomous_system_organization")] 57 | public string? AutonomousSystemOrganization { get; internal set; } = autonomousSystemOrganization; 58 | 59 | /// 60 | /// The name of the ISP associated with the IP address. 61 | /// 62 | [JsonInclude] 63 | [JsonPropertyName("isp")] 64 | public string? Isp { get; internal set; } = isp; 65 | 66 | /// 67 | /// The 68 | /// mobile country code (MCC) associated with the IP address and ISP. 69 | /// 70 | [JsonInclude] 71 | [JsonPropertyName("mobile_country_code")] 72 | public string? MobileCountryCode { get; internal set; } = mobileCountryCode; 73 | 74 | /// 75 | /// The 76 | /// mobile network code (MNC) associated with the IP address and ISP. 77 | /// 78 | [JsonInclude] 79 | [JsonPropertyName("mobile_network_code")] 80 | public string? MobileNetworkCode { get; internal set; } = mobileNetworkCode; 81 | 82 | /// 83 | /// The name of the organization associated with the IP address. 84 | /// 85 | [JsonInclude] 86 | [JsonPropertyName("organization")] 87 | public string? Organization { get; internal set; } = organization; 88 | 89 | /// 90 | /// The IP address that the data in the model is for. If you 91 | /// performed a "me" lookup against the web service, this will be the 92 | /// externally routable IP address for the system the code is running 93 | /// on. If the system is behind a NAT, this may differ from the IP 94 | /// address locally assigned to it. 95 | /// 96 | [JsonInclude] 97 | [JsonPropertyName("ip_address")] 98 | public string? IPAddress { get; internal set; } = ipAddress; 99 | 100 | /// 101 | /// The network associated with the record. In particular, this is 102 | /// the largest network where all of the fields besides 103 | /// IPAddress have the same value. 104 | /// 105 | [JsonInclude] 106 | [JsonPropertyName("network")] 107 | public Network? Network { get; internal set; } = network; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /MaxMind.GeoIP2/WebServiceClientOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace MaxMind.GeoIP2 4 | { 5 | /// 6 | /// Options class for WebServiceClient. 7 | /// 8 | public class WebServiceClientOptions 9 | { 10 | /// 11 | /// Your MaxMind account ID. 12 | /// 13 | public int AccountId { get; set; } 14 | 15 | /// 16 | /// Your MaxMind license key. 17 | /// 18 | public string LicenseKey { get; set; } = string.Empty; 19 | 20 | /// 21 | /// List of locale codes to use in name property from most preferred to least preferred. 22 | /// 23 | public IEnumerable? Locales { get; set; } 24 | 25 | /// 26 | /// Timeout in milliseconds for connection to web service. The default is 3000. 27 | /// 28 | public int Timeout { get; set; } = 3000; 29 | 30 | /// 31 | /// The host to use when accessing the service. 32 | /// 33 | public string Host { get; set; } = "geoip.maxmind.com"; 34 | 35 | /// 36 | /// If set, the client will use HTTP instead of HTTPS. Please note 37 | /// that MaxMind servers require HTTPS. 38 | /// 39 | public bool DisableHttps { get; set; } = false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /MaxMind.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxmind/GeoIP2-dotnet/42725a64c8eead3ca040a3e5a6feb80455f99eaa/MaxMind.snk -------------------------------------------------------------------------------- /README.dev.md: -------------------------------------------------------------------------------- 1 | ## Running Unit Tests on Linux 2 | 3 | 1. Install dotnet core, cli, and sdk 4 | 2. `MAXMIND_TEST_BASE_DIR="$PWD/GeoIP2.UnitTests" CONFIGURATION=Debug dev-bin` 5 | 6 | ## Publishing to NuGet 7 | 8 | 1. Review open issues and PRs to see if any can easily be fixed, closed, or 9 | merged. 10 | 2. Bump copyright year in `README.md` and the `AssemblyInfo.cs` files, if 11 | necessary. 12 | 3. Review `releasenotes.md` for completeness and correctness. Update its release 13 | date. 14 | 4. Run dev-bin/release.sh. This will build the project, generate docs, upload to 15 | NuGet, and make a GitHub release. 16 | 5. Update GitHub Release page for the release. 17 | 6. Verify the release on [NuGet](https://www.nuget.org/packages/MaxMind.GeoIP2/). 18 | -------------------------------------------------------------------------------- /dev-bin/release.ps1: -------------------------------------------------------------------------------- 1 | $ErrorActionPreference = 'Stop' 2 | $DebugPreference = 'Continue' 3 | 4 | $projectFile=(Get-Item "MaxMind.GeoIP2\MaxMind.GeoIP2.csproj").FullName 5 | $matches = (Get-Content -Encoding UTF8 releasenotes.md) ` | 6 | Select-String '(\d+\.\d+\.\d+(?:-\w+)?) \((\d{4}-\d{2}-\d{2})\)' ` 7 | 8 | $version = $matches.Matches.Groups[1].Value 9 | $date = $matches.Matches.Groups[2].Value 10 | 11 | if((Get-Date -format 'yyyy-MM-dd') -ne $date ) { 12 | Write-Error "$date is not today!" 13 | } 14 | 15 | $tag = "v$version" 16 | 17 | if (& git status --porcelain) { 18 | Write-Error '. is not clean' 19 | } 20 | 21 | (Get-Content -Encoding UTF8 $projectFile) ` 22 | -replace '(?<=)[^<]+', $version ` | 23 | Out-File -Encoding UTF8 $projectFile 24 | 25 | & git diff 26 | 27 | if ((Read-Host -Prompt 'Continue? (y/n)') -ne 'y') { 28 | Write-Error 'Aborting' 29 | } 30 | 31 | & git commit -m "$version" -a 32 | 33 | Push-Location MaxMind.GeoIP2 34 | 35 | & dotnet restore 36 | & dotnet build -c Release 37 | & dotnet pack -c Release 38 | 39 | Pop-Location 40 | 41 | Push-Location MaxMind.GeoIP2.UnitTests 42 | 43 | & dotnet restore 44 | & dotnet test -c Release 45 | 46 | Pop-Location 47 | 48 | if ((Read-Host -Prompt 'Continue given tests? (y/n)') -ne 'y') { 49 | Write-Error 'Aborting' 50 | } 51 | 52 | & git push -u origin HEAD 53 | 54 | if ((Read-Host -Prompt 'Should release? (y/n)') -ne 'y') { 55 | Write-Error 'Aborting' 56 | } 57 | 58 | & gh release create --target "$(git branch --show-current)" -t "$version" "$tag" 59 | 60 | & nuget push "MaxMind.GeoIP2/bin/Release/MaxMind.GeoIP2.$version.nupkg" -Source https://www.nuget.org/api/v2/package 61 | -------------------------------------------------------------------------------- /releasenotes.md: -------------------------------------------------------------------------------- 1 | GeoIP2 .NET API Release Notes 2 | ============================= 3 | 4 | 5.3.0 (2025-05-05) 5 | ------------------ 6 | 7 | * Support for the GeoIP Anonymous Plus database has been added. To do a 8 | lookup in this database, use the `AnonymousPlus` And `TryAnonymousPlus` 9 | methods on `DatabaseReader`. 10 | * .NET 6.0 and .NET 7.0 have been removed as targets as they have both 11 | reach their end of support from Microsoft. If you are using these versions, 12 | the .NET Standard 2.1 target should continue working for you. 13 | * .NET 9.0 has been added as a target. 14 | * `MetroCode` in `MaxMind.GeoIP2.Model.Location` has been marked `Obsolete`. 15 | The code values are no longer being maintained. 16 | 17 | 5.2.0 (2023-12-05) 18 | ------------------ 19 | 20 | * .NET 5.0 has been removed as a target as it has reach its end of life. 21 | However, if you are using .NET 5.0, the .NET Standard 2.1 target should 22 | continue working for you. 23 | * .NET 7.0 and .NET 8.0 have been added as a target. 24 | * The `IsAnycast` property was added to `MaxMind.GeoIP2.Model.Traits`. This 25 | returns `true` if the IP address belongs to an [anycast 26 | network](https://en.wikipedia.org/wiki/Anycast). This is available for the 27 | GeoIP2 Country, City Plus, and Insights web services and the GeoIP2 Country, 28 | City, and Enterprise databases. 29 | 30 | 5.1.0 (2022-02-04) 31 | ------------------ 32 | 33 | * Update System.Text.Json to 6.0.1 for .NET Standard 2.0 and 2.1. 34 | 35 | 5.0.0 (2022-02-04) 36 | ------------------ 37 | 38 | * This library no longer targets .NET 4.6.1. 39 | * .NET 6.0 was added as a target. 40 | * On .NET 5.0+, HttpClient is now used for synchronous requests instead of 41 | WebRequest. 42 | 43 | 4.1.0 (2021-11-19) 44 | ------------------ 45 | 46 | * Support for mobile country code (MCC) and mobile network codes (MNC) was 47 | added for the GeoIP2 ISP and Enterprise databases as well as the GeoIP2 48 | City and Insights web services. The `MobileCountryCode` and 49 | `MobileNetworkCode` properties were added to `MaxMind.GeoIP2.Responses.IspResponse` 50 | for the GeoIP2 ISP database and `MaxMind.GeoIP2.Model.Traits` for the 51 | Enterprise database and the GeoIP2 City and Insights web services. We expect 52 | this data to be available by late January, 2022. 53 | 54 | 4.0.1 (2020-11-19) 55 | ------------------ 56 | 57 | * This release fixes an issue with 4.0.0 where the synchronous web service 58 | methods could cause an unexpected JSON decoding error. There are no other 59 | changes. The async `WebServiceClient` methods and the `DatabaseReader` were 60 | not affected by the issue. 61 | 62 | 4.0.0 (2020-11-17) 63 | ------------------ 64 | 65 | * This library now requires .NET Framework 4.6.1 or greater or .NET Standard 66 | 2.0 or greater. 67 | * .NET 5.0 was added as a target framework. 68 | * `System.Text.Json` is now used for deserialization of web service requests. 69 | `Newtonsoft.Json` is no longer supported for serialization or 70 | deserialization. 71 | * The `Names` properties on `NamedEntity` models are now 72 | `IReadOnlyDictionary`. 73 | * The `Subdivisions` property on `CityResponse` and `InsightsResponse` is now 74 | an `IReadOnlyList`. 75 | * `GeoNameId` properties on `NamedEntity` models are now `long?` rather than 76 | `int?` to match the underlying database. 77 | * The `httpMessageHandler` argument is now correctly initialized by the 78 | `WebServiceClient` constructor. 79 | * The `Metadata` property was added to `IGeoIP2DatabaseReader`. Pull request 80 | by Mihai Valentin Caracostea. GitHub #134 & #135. 81 | 82 | 3.3.0 (2020-09-25) 83 | ------------------ 84 | 85 | * The `IsResidentialProxy` property has been added to 86 | `MaxMind.GeoIP2.Responses.AnonymousIPResponse` and 87 | `MaxMind.GeoIP2.Model.Traits`. 88 | 89 | 3.2.0 (2020-04-28) 90 | ------------------ 91 | 92 | * You may now create `WebServiceClient` as Typed Client with 93 | `IHttpClientFactory` in .NET Core 2.1+. Pull Request by Bojan Nikolić. 94 | GitHub #115 & #117. 95 | * The `WebServiceClient` constructor now supports an optional 96 | `httpMessageHandler` parameter. This is used in creating the `HttpClient` 97 | for asynchronous requests. 98 | 99 | 3.1.0 (2019-12-06) 100 | ------------------ 101 | 102 | * This library has been updated to support the nullable reference types 103 | introduced in C# 8.0. 104 | * A `Network` property has been added to the various response models. This 105 | represents the largest network where all the fields besides the IP 106 | address are the same. 107 | * The `StaticIPScore` property has been added to `MaxMind.GeoIP2.Model.Traits`. 108 | This output is available from GeoIP2 Precision Insights. It is an indicator 109 | of how static or dynamic an IP address is. 110 | * The `UserCount` property has been added to `MaxMind.GeoIP2.Model.Traits`. 111 | This output is available from GeoIP2 Precision Insights. It is an 112 | estimate of the number of users sharing the IP/network over the past 113 | 24 hours. 114 | * Updated documentation of anonymizer properties - `IsAnonymousVpn` and 115 | `IsHostingProvider` - to be more descriptive. 116 | * `netstandard2.1` was added as a target framework. 117 | 118 | 3.0.0 (2018-04-11) 119 | ------------------ 120 | 121 | * The `userId` constructor parameter for `WebServiceClient` was renamed to 122 | `accountId` and support was added for the error codes `ACCOUNT_ID_REQUIRED` 123 | and `ACCOUNT_ID_UNKNOWN`. 124 | * The exception classes are no longer serializable when using the .NET 125 | Framework. This eliminates a difference between the .NET Framework 126 | assemblies and the .NET Standard ones. 127 | * The `AutonomousSystemNumber` properties on `MaxMind.GeoIP2.Model.Traits`, 128 | `MaxMind.GeoIP2.Responses.AsnResponse`, and 129 | `MaxMind.GeoIP2.Responses.IspResponse` are now `long?` to match the underlying 130 | types in the databases. 131 | * `MaxMind.Db` was upgraded to 2.4.0. This adds a new file mode enum value for 132 | the database reader, `FileAccessMode.MemoryMappedGlobal`. When used, this will 133 | open the file in global memory map mode. This requires the "create global 134 | objects" right. 135 | 136 | 2.10.0 (2018-01-19) 137 | ------------------- 138 | 139 | * The `IsInEuropeanUnion` property was added to `MaxMind.GeoIP2.Model.Country` 140 | and `MaxMind.GeoIP2.Model.RepresentedCountry`. This property is `true` if the 141 | country is a member state of the European Union. 142 | 143 | 2.9.0 (2017-10-27) 144 | ------------------ 145 | 146 | * The following new anonymizer properties were added to 147 | `MaxMind.GeoIP2.Model.Traits` for use with GeoIP2 Precision Insights: 148 | `IsAnonymous`, `IsAnonymousVpn`, `IsHostingProvider`, `IsPublicProxy`, 149 | and `IsTorExitNode`. 150 | * Deserialization of the registered country when reading a GeoLite2 Country or 151 | GeoIP2 Country database now works. Previously, it was deserialized to the 152 | wrong name. Reported by oliverherdener. 153 | * A `netstandard2.0` target was added to eliminate additional dependencies 154 | required by the `netstandard1.4` target. Pull request by Adeel Mujahid. 155 | GitHub #81. 156 | * As part of the above work, the separate Mono build files were dropped. As 157 | of Mono 5.0.0, `msbuild` is supported. 158 | 159 | 2.8.0 (2017-05-08) 160 | ------------------ 161 | 162 | * Add support for GeoLite2 ASN. 163 | * Switch to the updated MSBuild .NET Core build system. 164 | * Move tests from NUnit to xUnit.net. 165 | * Upgrade to `MaxMind.Db` 2.2.0. 166 | 167 | 2.7.2 (2016-11-22) 168 | ------------------ 169 | 170 | * Use framework assembly for `System.Net.Http` on .NET 4.5. 171 | * Update for .NET Core 1.1. 172 | 173 | 2.7.1 (2016-08-08) 174 | ------------------ 175 | 176 | * Re-release of 2.7.0 to fix strong name issue. No code changes. 177 | 178 | 2.7.0 (2016-08-01) 179 | ------------------ 180 | 181 | * First non-beta release with .NET Core support. 182 | * The tests now use the .NET Core NUnit runner. Pull request by Adeel Mujahid. 183 | GitHub #68. 184 | * Updated documentation to clarify what the accuracy radius refers to. 185 | 186 | 2.7.0-beta2 (2016-06-02) 187 | ------------------------ 188 | 189 | * Added handling of additional error codes that the web service may return. 190 | * Update for .NET Core RC2. Pull request by Adeel Mujahid. GitHub #64. 191 | 192 | 2.7.0-beta1 (2016-05-15) 193 | ------------------------ 194 | 195 | * .NET Core support. Switched to `dotnet/cli` for building. Pull request by 196 | Adeel Mujahid. GitHub #60. 197 | * Updated documentation to reflect that the accuracy radius is now included 198 | in City. 199 | 200 | 2.6.0 (2016-04-15) 201 | ------------------ 202 | 203 | * Added support for the GeoIP2 Enterprise database. 204 | 205 | 2.6.0-beta3 (2016-02-10) 206 | ------------------------ 207 | 208 | * Try-based lookup methods were added to `DatabaseReader` as an alternative to 209 | the existing methods. These methods return a boolean indicating whether the 210 | record was found rather than throwing an exception when it is not found. 211 | Pull request by Mani Gandham. GitHub #31, #50. 212 | 213 | 2.6.0-beta2 (2016-01-18) 214 | ------------------------ 215 | 216 | * Parameterless endpoint methods were added to `WebServiceClient`. These 217 | return the record for the requesting IP address using the `me` endpoint as 218 | documented in the web services API documentation. 219 | * The target framework is now .NET 4.5 rather than 4.5.2 in order to work 220 | better with Mono. GitHub #44. 221 | 222 | 2.6.0-beta1 (2016-01-18) 223 | ------------------------ 224 | 225 | * Upgrade MaxMindb.Db reader to 2.0.0-beta1. This includes significant 226 | performance increases. 227 | 228 | 2.5.0 (2015-12-04) 229 | ------------------ 230 | 231 | * IMPORTANT: The target framework is now 4.5.2. Microsoft is ending support 232 | for 4.0, 4.5, and 4.5.1 on January 12, 2016. Removing support for these 233 | frameworks allows us to remove the dependency on the BCL libraries and fixes 234 | several outstanding issues. Closes #38, #39, #40, and #42. 235 | * The assembly version was bumped to 2.5.0. 236 | * Classes subclassing `NamedEntity` now have a default locale of `en`. This 237 | allows the `Name` property to be used (for English names) when the object is 238 | deserialized from JSON. Closes #41. 239 | * The `locale` parameter for the `DatabaseReader` and `WebServiceClient` 240 | constructors is now an `IEnumerable` rather than a `List`. 241 | * The tests now use NUnit 3. 242 | 243 | 2.4.0 (2015-09-23) 244 | ------------------ 245 | 246 | * Updated MaxMind.Db to 1.2.0. 247 | 248 | 2.4.0-beta1 (2015-09-10) 249 | ------------------------ 250 | 251 | * Async support was added to the `WebServiceClient`. Each web-service end 252 | point now has a corresponding `*Async(ip)` method. GitHub #1. 253 | * Use of RestSharp was replaced by `HttpWebRequest` for synchronous HTTP 254 | requests and `HttpClient` for asynchronous requests. Microsoft BCL libraries 255 | and `System.Net.Http` are used to provide `async`/`await` and `HttpClient` 256 | support on .NET 4.0. GitHub #33. 257 | * The library now has a strong name. 258 | 259 | 2.3.1 (2015-07-21) 260 | ------------------ 261 | 262 | * Upgrade to MaxMind.Db 1.1.0. 263 | * Fix serialization on exceptions. 264 | 265 | 2.3.1-beta1 (2015-06-30) 266 | ------------------------ 267 | 268 | * Upgrade to Json.NET 7.0.1. 269 | * Upgrade to MaxMind.Db 1.1.0-beta1. This release includes a number of 270 | significant improvements for the memory-mapped file mode. 271 | 272 | 2.3.0 (2015-06-29) 273 | ------------------ 274 | 275 | * `AverageIncome` and `PopulationDensity` were added to the `Location` 276 | model for use with the new fields in GeoIP2 Insights. 277 | * `IsAnonymousProxy` and `IsSatelliteProvider` in `MaxMind.GeoIP2.Model.Traits` 278 | have been deprecated. Please use our [GeoIP2 Anonymous IP 279 | database](https://www.maxmind.com/en/geoip2-anonymous-ip-database) to 280 | determine whether an IP address is used by an anonymizing service. 281 | 282 | 2.2.0 (2015-05-19) 283 | ------------------ 284 | 285 | * All of the database methods in `DatabaseReader` and all of the web service 286 | methods in `WebServiceClient` now have a counterpart that takes an 287 | `IPAddress` instead of a `string`. Pull request by Guillaume Turri. GitHub 288 | #24. 289 | * The `JsonIgnore` attribute was added to `Names` in `NamedEntity` and 290 | `Subdivisions` in `AbstractCityResponse` as these were already exposed to 291 | JSON.NET through the private field backing them. Pull request by Dan Byrne 292 | GitHub #21. 293 | * The interfaces `IGeoIP2DatabaseReader` and `IGeoIP2WebServicesClient` were 294 | added to facilitate dependency injection and mocking. Pull request by Naz 295 | Soogund. GitHub #22. 296 | * A `HasCoordinates` getter was added to the `Location` class. This will 297 | return true if both the `Latitude` and `Longitude` have values. Pull request 298 | by Darren Hickling. GitHub #23. 299 | * All of the response and model properties now set the appropriate 300 | `JsonProperty` rather than relying an JSON.NET's automatic matching. 301 | Serializing these objects should now product JSON much more similar to the 302 | JSON returned by the web service and internal structure of the data in 303 | database files. 304 | * Dependencies were updated to most recent versions. 305 | 306 | 2.1.0 (2014-11-06) 307 | ------------------ 308 | 309 | * Added support for the GeoIP2 Anonymous IP database. The `DatabaseReader` 310 | class now has an `AnonymousIP()` method which returns an 311 | `AnonymousIPResponse` object. 312 | 313 | 2.0.0 (2014-09-29) 314 | ------------------ 315 | 316 | * First production release. 317 | 318 | 0.5.0 (2014-09-24) 319 | ------------------ 320 | 321 | * The deprecated `CityIspOrg` and `Omni` methods were removed. 322 | * `DatabaseReader` methods will now throw an `InvalidOperationException` when 323 | called for the wrong database type. 324 | * `DatabaseReader` now has a `Metadata` property that provides an object 325 | containing the metadata for the open database. 326 | 327 | 0.4.0 (2014-07-22) 328 | ------------------ 329 | 330 | * The web service client API has been updated for the v2.1 release of the web 331 | service. In particular, the `CityIspOrg` and `Omni` methods on 332 | `WebServiceClient` have been deprecated. The `City` method now provides all 333 | of the data formerly provided by `CityIspOrg`, and the `Omni` method has 334 | been replaced by the `Insights` method. 335 | * Support was added for the GeoIP2 Connection Type, Domain, and ISP databases. 336 | 337 | 338 | 0.3.3 (2014-06-02) 339 | ------------------ 340 | 341 | * Constructors with named parameters were added to the model and response 342 | classes. (Jon Wynveen) 343 | 344 | 0.3.2 (2014-04-09) 345 | ------------------ 346 | 347 | * A constructor taking a `Stream` was added to `DatabaseReader`. 348 | * Fixed dependency on wrong version of `Newtonsoft.Json`. 349 | 350 | 0.3.1 (2014-02-13) 351 | ------------------ 352 | 353 | * Fixed broken error handling. Previously the wrong exceptions and error 354 | messages were returned for some web service errors. 355 | 356 | 0.3.0 (2013-11-15) 357 | ------------------ 358 | 359 | * API CHANGE: Renamed exceptions to remove GeoIP2 prefixes. 360 | * Improved error messages when RestSharp does not return an HTTP status code. 361 | 362 | 0.2.0 (2013-10-25) 363 | ------------------ 364 | 365 | * First release with GeoIP2 database support. See `DatabaseReader` class. 366 | 367 | 0.1.1 (2013-10-04) 368 | ------------------ 369 | 370 | * Build documentation. 371 | 372 | 0.1.0 (2013-09-20) 373 | ------------------ 374 | 375 | * Initial release. 376 | --------------------------------------------------------------------------------