How to determine if an IP address belongs to a country
Asked Answered
P

11

25

How would i determine the country that a spcific IP address is originating from using c#. I need to use this to check if connections originate from a specific country.

Pennypennyaliner answered 13/8, 2009 at 4:58 Comment(1)
I need the data to be available offline since it will be used for stats. Because of this will i will be using the sql optionPennypennyaliner
D
29

You can use this SQL data in your project to determine that: IP address geolocation SQL database. Download that data and import it into your database to run checks locally.

Or you can use their free API that returns XML containing the country code and country name. You'd make a request to the following URL with the IP address you wanted to check, as seen in this example:

http://ipinfodb.com/ip_query_country.php?ip=74.125.45.100

Returns:

<Response>
<Ip>74.125.45.100</Ip>
<Status>OK</Status>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
</Response>
Durham answered 13/8, 2009 at 5:1 Comment(3)
Please note that the IP assignments change occasionally. So remember to update your database occasionally. (The frequency of updates you need depends on what you're doing; for simple stats you may decide that annual updates are OK).Tenorrhaphy
This has now changed: you have to register now (free) to be able to use their API. See here: ipinfodb.com/ip_location_api.phpVerine
It looks like this has changed since, the site now has a link in the main navigation eventually leads to the following for downloading: download.ip2location.com/lite Attribution required but free for commercial use. Additional info here (ie. IP's must be converted to INT's): lite.ip2location.com/database-ip-countryMarasmus
V
3

Here is a free IP Address to Country database.

Villain answered 13/8, 2009 at 5:4 Comment(0)
J
2

you can ask google to do it for you.

there are also services that you can pay for you want:

Jalousie answered 13/8, 2009 at 5:2 Comment(0)
H
1

If you don't want to use an API like perhaps hostip.info, then I'd suggest subscribing to maxmind and running a host lookup database locally.

Hulbard answered 13/8, 2009 at 5:2 Comment(0)
T
1

ip2cc - Lookup country and Russia region by IP address Python module with script to create database from up-to-date official data.

This Python utility loads (as frequently as you like) up-to-date information from Regional Internet Registry sites (arin, ripencc, apnic, lacnic, afrinic), as shown in the source:

url_template = 'ftp://ftp.ripe.net/pub/stats/%s/delegated-%s-latest'
sources = {}
for name in ('arin', 'ripencc', 'apnic', 'lacnic', 'afrinic'):
    sources[name] = url_template % (name, name)

Once the data is loaded, queries can be answered offline and very quickly. Can be easily modified to directly answer the original question, or used from the command line to return the country an IP address belongs to.

Tournament answered 13/8, 2009 at 5:27 Comment(0)
J
1

For offline database, you can get the free IP2Location LITE DB1

To create the table

CREATE DATABASE ip2location
GO

USE ip2location
GO

CREATE TABLE [ip2location].[dbo].[ip2location_db1](
    [ip_from] float NOT NULL,
    [ip_to] float NOT NULL,
    [country_code] nvarchar(2) NOT NULL,
    [country_name] nvarchar(64) NOT NULL,
) ON [PRIMARY]
GO

CREATE INDEX [ip_from] ON [ip2location].[dbo].[ip2location_db1]([ip_from]) ON [PRIMARY]
GO

CREATE INDEX [ip_to] ON [ip2location].[dbo].[ip2location_db1]([ip_to]) ON [PRIMARY]
GO

To import the data

BULK INSERT [ip2location].[dbo].[ip2location_db1]
    FROM 'C:\[path to your CSV file]\IP2LOCATION-LITE-DB1.CSV'
    WITH
    (
        FORMATFILE = 'C:\[path to your DB1.FMT file]\DB1.FMT'
    )
GO

For the FMT file

10.0
5
1 SQLCHAR 0 1 "\"" 0 first_double_quote  Latin1_General_CI_AI
2 SQLCHAR 0 20 "\",\"" 1 ip_from ""
3 SQLCHAR 0 20 "\",\"" 2 ip_to ""
4 SQLCHAR 0 2 "\",\"" 3 country_code Latin1_General_CI_AI
5 SQLCHAR 0 64 "\"\r\n" 4 country_name Latin1_General_CI_AI

The first line of the FMT code indicates the version of bcp. Please change the version as according to your MS-SQL installed.

SQL Server 2016 12.0

SQL Server 2014 12.0

SQL Server 2012 11.0

SQL Server 2008/2008 R2 10.0

SQL Server 2005 9.0

SQL Server 2000 8.0

SQL Server 7.0 7.0

SQL Server 6.5 6.5

C# code to query MSSQL

using System.Data.SqlClient;
using System.Numerics;
using System.Net;
using System.Text;
public class Form1 {

    private void Form1_Load(object sender, System.EventArgs e) {
        string ip = "8.8.8.8";
        this.IP2Location(ip);
    }

    private void IP2Location(string myip) {
        IPAddress address = null;
        if (IPAddress.TryParse(myip, address)) {
            byte[] addrBytes = address.GetAddressBytes();
            this.LittleEndian(addrBytes);
            UInt32 ipno = 0;
            ipno = BitConverter.ToUInt32(addrBytes, 0);
            string sql = "SELECT TOP 1 * FROM ip2location_db1 WHERE ip_to >= \'" + ipno.ToString() + "\'";
            object conn = new SqlConnection("Server=yourserver;Database=yourdatabase;User Id=youruserid;Password=yourpassword;");
            object comm = new SqlCommand(sql, conn);
            SqlDataReader reader;
            comm.Connection.Open();
            reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
            int x = 0;
            object sb = new StringBuilder(250);
            if (reader.HasRows) {
                if (reader.Read()) {
                    for (x = 0; (x <= (reader.FieldCount() - 1)); x++) {
                        sb.Append((reader.GetName(x) + (": " + (reader.GetValue(x) + "\r\n"))));
                    }
                }
            }

            reader.Close();
            MsgBox(sb.ToString());
        }

    }

    private void LittleEndian(ref byte[] byteArr) {
        if (BitConverter.IsLittleEndian) {
            List<byte> byteList = new List<byte>(byteArr);
            byteList.Reverse();
            byteArr = byteList.ToArray();
        }

    }
}
Jonna answered 26/2, 2018 at 8:50 Comment(0)
B
0

Another service you could use is my own, http://ipinfo.io, which returns location, organization and other information:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "loc": "37.385999999999996,-122.0838",
  "org": "AS15169 Google Inc.",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "phone": 650
}

See http://ipinfo.io/developers for more information.

Belayneh answered 30/8, 2014 at 2:40 Comment(0)
I
0

Here's how to do this with https://ipdata.co

//Common testing requirement. If you are consuming an API in a sandbox/test region, uncomment this line of code ONLY for non production uses.
//System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

//Be sure to run "Install-Package Microsoft.Net.Http" from your nuget command line.
using System;
using System.Net.Http;

var baseAddress = new Uri("https://api.ipdata.co/78.8.53.5");

using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
{

  httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");

  using(var response = await httpClient.GetAsync("undefined"))
  {

        string responseData = await response.Content.ReadAsStringAsync();
  }
}

Via Curl

curl https://api.ipdata.co/78.8.53.5
{
    "ip": "78.8.53.5",
    "city": "G\u0142og\u00f3w",
    "region": "Lower Silesia",
    "region_code": "DS",
    "country_name": "Poland",
    "country_code": "PL",
    "continent_name": "Europe",
    "continent_code": "EU",
    "latitude": 51.6461,
    "longitude": 16.1678,
    "asn": "AS12741",
    "organisation": "Netia SA",
    "postal": "67-200",
    "currency": "PLN",
    "currency_symbol": "z\u0142",
    "calling_code": "48",
    "flag": "https://ipdata.co/flags/pl.png",
    "emoji_flag": "\ud83c\uddf5\ud83c\uddf1",
    "time_zone": "Europe/Warsaw",
    "is_eu": true,
    "suspicious_factors": {
        "is_tor": false
    }
}⏎ 
Illuminism answered 18/2, 2018 at 20:22 Comment(0)
L
0

You can easily do this using an IP Geolocation API

It will return the country, state, city, timezone, and postal code. Also, visit https://geo.ipify.org/docs and try for free. Let me know how it goes.

Lysimeter answered 24/11, 2019 at 10:48 Comment(0)
R
0

You can easily lookup any IP address using https://astroip.co

In C#:

var url = "https://api.astroip.co/70.167.7.1/?api_key=1725e47c-1486-4369-aaff-463cc9764026";

using (var httpClient = new HttpClient())
using(var resp = await httpClient.GetAsync(url))
{
    string resp = await resp.Content.ReadAsStringAsync();
 }

In curl:

curl https://api.astroip.co/70.167.7.1/?api_key=1725e47c-1486-4369-aaff-463cc9764026

{
  "status_code": 200,
  "geo": {
    "is_metric": false,
    "is_eu": false,
    "longitude": -97.822,
    "latitude": 37.751,
    "country_geo_id": 6252001,
    "zip_code": null,
    "city": null,
    "region_code": null,
    "region_name": null,
    "continent_code": "NA",
    "continent_name": "North America",
    "capital": "Washington",
    "country_name": "United States",
    "country_code": "US"
  },
  "asn": {
    "route": "70.167.6.0/23",
    "type": "isp",
    "domain": "cox.net",
    "organization": "ASN-CXA-ALL-CCI-22773-RDC",
    "asn": "AS22773"
  },
  "currency": {
    "native_name": "US Dollar",
    "code": "USD",
    "name": "US Dollar",
    "symbol": "$"
  },
  "timezone": {
    "is_dst": false,
    "gmt_offset": -21600,
    "date_time": "2020-11-23T15:15:56-06:00",
    "microsoft_name": "Central Standard Time",
    "iana_name": "America/Chicago"
  },
  "security": {
    "is_crawler": false,
    "is_proxy": false,
    "is_tor": false,
    "tor_insights": null,
    "proxy_insights": null,
    "crawler_insights": null
  },
  "crypto": null,
  "user_agent": null,
  "error": null,
  "hostname": "wsip-70-167-7-1.sd.sd.cox.net",
  "ip_type": "ipv4",
  "ip": "70.167.7.1"
}
Rutharuthann answered 23/11, 2020 at 21:21 Comment(0)
C
0

Here is an extension class for converting an IPAddress to UInt32. Code refactored from @vlam's answer

using System.Net;

namespace Module.IP2Location.Core.Extensions;

public static class IPAddressExtensions
{

    public static UInt32 ToUInt(this IPAddress address)
    {

        byte[] addrBytes = address.GetAddressBytes();
        if (BitConverter.IsLittleEndian)
        {
            List<byte> byteList = new List<byte>(addrBytes);
            byteList.Reverse();
            addrBytes = byteList.ToArray();
        }
        UInt32 ipno = 0;
        ipno = BitConverter.ToUInt32(addrBytes, 0);
        return ipno;
    }

}
Chopin answered 6/12, 2021 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.