IPGeolocation.io .NET SDK


Overview

Official .NET SDK for the IPGeolocation.io IP Geolocation API.

Look up IPv4, IPv6, and domains with /v3/ipgeo and /v3/ipgeo-bulk. Get geolocation, company, ASN, time zone, network, hostname, abuse, user-agent, and security data from one API.

  • .NET Standard 2.1 package
  • Async client built on HttpClient
  • Typed responses plus raw JSON and XML methods

Install

dotnet add package IPGeoLocation.IPGeolocation
Install-Package IPGeoLocation.IPGeolocation
<PackageReference Include="IPGeoLocation.IPGeolocation" Version="3.0.1" />

Quick Start

using System;
using IPGeolocation;

var apiKey = Environment.GetEnvironmentVariable("IPGEO_API_KEY")
    ?? throw new InvalidOperationException("Set IPGEO_API_KEY first.");

using var client = new IpGeolocationClient(new IpGeolocationClientConfig(apiKey: apiKey));

var response = await client.LookupIpGeolocationAsync(
    new LookupIpGeolocationRequest(ip: "8.8.8.8"));

Console.WriteLine(response.Data.Ip); // 8.8.8.8
Console.WriteLine(response.Data.Location?.CountryName); // United States
Console.WriteLine(response.Data.Location?.City);
Console.WriteLine(response.Data.TimeZone?.Name);
Console.WriteLine(response.Metadata.CreditsCharged ?? 0);

Use LookupIpGeolocationRequest and BulkLookupIpGeolocationRequest when you want request validation before the call is sent.


At a Glance

ItemValue
PackageIPGeoLocation.IPGeolocation
NamespaceIPGeolocation
Supported Endpoints/v3/ipgeo, /v3/ipgeo-bulk
Supported InputsIPv4, IPv6, domain
Main Data ReturnedGeolocation, company, ASN, time zone, network, hostname, abuse, user-agent, currency, security
AuthenticationAPI key, request-origin auth for /v3/ipgeo only
Response FormatsStructured JSON, raw JSON, raw XML
Bulk LimitUp to 50,000 IPs or domains per request
TransportHttpClient

Get Your API Key

Create an IPGeolocation.io account and copy an API key from your dashboard.

  1. Sign up: https://app.ipgeolocation.io/signup
  2. Verify your email if prompted
  3. Sign in: https://app.ipgeolocation.io/login
  4. Open your dashboard: https://app.ipgeolocation.io/dashboard
  5. Copy an API key from the API Keys section

For server-side code, keep the API key in an environment variable or secret manager. For browser-based single lookups on paid plans, use request-origin auth instead of exposing an API key in frontend code.


Authentication


1. API Key

using IPGeolocation;

using var client = new IpGeolocationClient(
    new IpGeolocationClientConfig(apiKey: Environment.GetEnvironmentVariable("IPGEO_API_KEY")));

2. Request-Origin Auth

using IPGeolocation;

using var client = new IpGeolocationClient(
    new IpGeolocationClientConfig(requestOrigin: "https://app.example.com"));

requestOrigin must be an absolute http or https origin with no path, query string, fragment, or userinfo.


Plan Behavior

Feature availability depends on your plan and request parameters.

CapabilityFreePaid
Single IPv4 and IPv6 lookupSupportedSupported
Domain lookupNot supportedSupported
Bulk lookupNot supportedSupported
Non-English langNot supportedSupported
Request-origin authNot supportedSupported for /v3/ipgeo only
Optional modules via includeNot supportedSupported
include: ["*"]Base response onlyAll plan-available modules

Paid plans still need the include parameter for optional modules. fields and excludes only trim the response. They do not turn modules on or unlock paid data.


Client Configuration

FieldTypeDefaultNotes
apiKeystring?unsetRequired for bulk lookup. Optional for single lookup if requestOrigin is set.
requestOriginstring?unsetMust be an absolute http or https origin.
baseUrlstringhttps://api.ipgeolocation.ioOverride the API base URL.
connectTimeoutTimeSpan10 secondsTime to connect and receive response headers.
readTimeoutTimeSpan30 secondsTime to wait for the next part of the response.

The client constructor accepts an IpGeolocationClientConfig. Both timeouts must be greater than zero.


Available Methods

MethodReturnsNotes
LookupIpGeolocationAsync(request = null, cancellationToken = default)Task<ApiResponse<IpGeolocationResponse>>Single lookup. Typed JSON response.
LookupIpGeolocationRawAsync(request = null, cancellationToken = default)Task<ApiResponse<string>>Single lookup. Raw JSON or XML string.
BulkLookupIpGeolocationAsync(request, cancellationToken = default)Task<ApiResponse<IReadOnlyList<BulkLookupResult>>>Bulk lookup. Typed JSON response.
BulkLookupIpGeolocationRawAsync(request, cancellationToken = default)Task<ApiResponse<string>>Bulk lookup. Raw JSON or XML string.
Dispose()voidCloses the client and releases its transport.

Request Options

FieldApplies ToNotes
ipSingle lookupIPv4, IPv6, or domain. Omit it for caller IP lookup.
ipsBulk lookupCollection of 1 to 50,000 IPs or domains.
langSingle and bulkOne of en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt, ar.
includeSingle and bulkCollection of module names such as security, abuse, user_agent, hostname, liveHostname, hostnameFallbackLive, geo_accuracy, dma_code, or *.
fieldsSingle and bulkCollection of field paths to keep, for example location.country_name or security.threat_score.
excludesSingle and bulkCollection of field paths to remove from the response.
userAgentSingle and bulkOverrides the outbound User-Agent header.
headersSingle and bulkExtra request headers as IReadOnlyDictionary<string, string>.
outputSingle and bulkResponseFormat.Json or ResponseFormat.Xml. Typed methods require JSON.

Examples

The examples below assume you already have a configured client in scope:

using System;
using System.Linq;
using IPGeolocation;

var apiKey = Environment.GetEnvironmentVariable("IPGEO_API_KEY")
    ?? throw new InvalidOperationException("Set IPGEO_API_KEY first.");

using var client = new IpGeolocationClient(new IpGeolocationClientConfig(apiKey: apiKey));

1. Caller IP

Omit ip to look up the public IP of the machine making the request.

var response = await client.LookupIpGeolocationAsync();
Console.WriteLine(response.Data.Ip);

2. Domain Lookup

Domain lookup is a paid-plan feature.

var response = await client.LookupIpGeolocationAsync(
    new LookupIpGeolocationRequest(ip: "ipgeolocation.io"));

Console.WriteLine(response.Data.Ip);
Console.WriteLine(response.Data.Domain); // ipgeolocation.io
Console.WriteLine(response.Data.Location?.CountryName);

3. Security and Abuse

var response = await client.LookupIpGeolocationAsync(
    new LookupIpGeolocationRequest(
        ip: "9.9.9.9",
        include: new[] { "security", "abuse" }));

Console.WriteLine(response.Data.Security?.ThreatScore);
Console.WriteLine(response.Data.Abuse?.Emails?.FirstOrDefault());

4. User-Agent Parsing

To parse a visitor user-agent string, pass include: ["user_agent"] and send the visitor string in the request User-Agent header.

using System.Collections.Generic;

const string visitorUa =
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9";

var response = await client.LookupIpGeolocationAsync(
    new LookupIpGeolocationRequest(
        ip: "115.240.90.163",
        include: new[] { "user_agent" },
        headers: new Dictionary<string, string> { ["User-Agent"] = visitorUa }));

Console.WriteLine(response.Data.UserAgent?.Name);
Console.WriteLine(response.Data.UserAgent?.OperatingSystem?.Name);

5. Filtered Response

var response = await client.LookupIpGeolocationAsync(
    new LookupIpGeolocationRequest(
        ip: "8.8.8.8",
        include: new[] { "security" },
        fields: new[] { "location.country_name", "security.threat_score", "security.is_vpn" },
        excludes: new[] { "currency" }));

Console.WriteLine(response.Data.Location?.CountryName);
Console.WriteLine(response.Data.Security?.ThreatScore);
Console.WriteLine(response.Data.Security?.IsVpn);
Console.WriteLine(response.Data.Currency is null); // True

6. Raw XML

var response = await client.LookupIpGeolocationRawAsync(
    new LookupIpGeolocationRequest(
        ip: "8.8.8.8",
        output: ResponseFormat.Xml));

Console.WriteLine(response.Data);

7. Bulk Lookup

var response = await client.BulkLookupIpGeolocationAsync(
    new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8", "1.1.1.1" }));

foreach (var result in response.Data)
{
    if (result is BulkLookupSuccess success)
    {
        Console.WriteLine(success.Data.Ip);
        continue;
    }

    if (result is BulkLookupError error)
    {
        Console.WriteLine(error.Error.Message);
    }
}

8. Raw Bulk JSON

var response = await client.BulkLookupIpGeolocationRawAsync(
    new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8", "1.1.1.1" }));

Console.WriteLine(response.Data);

Response Metadata

Every method returns ApiResponse<T>, where:

  • Data contains the typed object or raw response string
  • Metadata contains response details such as:
    • CreditsCharged
    • SuccessfulRecords
    • StatusCode
    • DurationMs
    • RawHeaders

Example:

Console.WriteLine(response.Metadata.StatusCode);
Console.WriteLine(response.Metadata.DurationMs);
Console.WriteLine(response.Metadata.FirstHeaderValue("content-type"));

Errors

The SDK throws typed exceptions instead of returning error objects for failed HTTP responses. SDK error messages replace your configured API key with [REDACTED]. SDK error types and HTTP status codes stay the same. Some technical error details may be shortened to keep the key hidden.

ExceptionWhen It Happens
ValidationExceptionInvalid config, invalid request values, or typed XML request
RequestTimeoutExceptionConnect timeout or read timeout
TransportExceptionNetwork or transport failure
SerializationExceptionRequest or response serialization failure
ApiExceptionAPI returned a non-2xx response

ApiException has status-specific subclasses:

  • BadRequestException
  • UnauthorizedException
  • ForbiddenException
  • NotFoundException
  • MethodNotAllowedException
  • ContentTooLargeException
  • UnsupportedMediaTypeException
  • LockedException
  • TooManyRequestsException
  • CustomStatus499Exception
  • InternalServerErrorException

Example:

try
{
    var response = await client.LookupIpGeolocationAsync(
        new LookupIpGeolocationRequest(output: ResponseFormat.Xml));
}
catch (ValidationException error)
{
    Console.WriteLine(error.Message);
}
catch (ApiException error)
{
    Console.WriteLine((int)error.StatusCode);
    Console.WriteLine(error.Message);
}

Troubleshooting

  • Bulk lookup always requires apiKey. requestOrigin is not enough.
  • Typed methods only support JSON. Use the raw methods for XML.
  • If you need security, abuse, user-agent, or hostname data, include those modules explicitly.
  • fields and excludes filter the response. They do not unlock paid data.
  • requestOrigin must be an origin only. Do not include a path, query string, fragment, or userinfo.

Frequently Asked Questions

Only for single lookup with paid-plan request-origin auth. Bulk lookup always requires an API key.
No. Typed methods only support JSON. Use LookupIpGeolocationRawAsync or BulkLookupIpGeolocationRawAsync for XML.
No. Domain lookup is a paid-plan feature.
Pass the right modules in include, for example security, abuse, hostname, or user_agent.

Links

Subscribe to Our Newsletter

Get the latest in geolocation tech, straight to your inbox.