Getting Location from an IP Address
The Ipregistry API enables geolocation lookup for IPv4 or IPv6 addresses. It includes the country, city, region, postal code, borders, population but also carrier data, company, domain name and more.
Below are some common usage patterns for a variety of programming languages and libraries:
Make sure to replace
tryout
by your own API key before using the following examples in production. The tryout API key used in these examples is heavily rate limited and is meant only for a few initial tests.Most code snippets provided hereafter make use of the origin endpoint. This endpoint returns IP info for the device that runs the code. If the code is run on client-side, it's most probably what you want. If you run the code on server-side, then you should use the single lookup endpoint by passing the client IP in the URL as follows:
https://api.ipregistry.co/1.2.3.4?key=tryout
where 1.2.3.4
is the client IP address you want to get information for. How to retrieve the client IP address from your server depends on the technology used but usually, you have a header that you can parse such as X-Forwarded-For
.The following code snippets are basic and do not handle possible error cases. For advanced use cases, we recommend using Ipregistry client libraries.
Bash (using cURL)
country=$(curl -s "https://api.ipregistry.co/?key=tryout" | jq ".location.country.name")
echo "Your country is: $country"
C# (using RestSharp)
var client = new RestClient("https://api.ipregistry.co/?key=tryout");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Go
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.ipregistry.co/1.2.3.4"
method := "GET"
client := &http.Client {
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
fmt.Println(err)
}
req.Header.Add("Authorization", "ApiKey tryout")
res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
Javascript (Vanilla)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var json = JSON.parse(request.responseText);
console.log('Your country is ' + json['location']['country']['name']);
}
};
request.open('GET', 'https://api.ipregistry.co/?key=tryout', true);
request.send(null);
Javascript (using Fetch)
fetch('https://api.ipregistry.co/?key=tryout')
.then(function (response) {
return response.json();
})
.then(function (json) {
console.log('Your country is ' + json['location']['country']['name']);
});
jQuery
$.getJSON( "https://api.ipregistry.co/?key=tryout", function (json) {
console.log("Your country is " + json['location']['country']['name'])
});
PHP
Single IP lookup
$curl = curl_init();
$clientIp = $_SERVER['REMOTE_ADDR'];
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.ipregistry.co/" . $clientIp . "?key=tryout",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "An error occurred while retrieving IP info:" . $err;
} else {
$ipinfo = json_decode($response, true);
$countryCode = $ipinfo['location']['country']['code'];
echo $countryCode;
}
Batch IP lookup
$curl = curl_init();
$ips = array("66.165.2.7", "1.1.1.1", "8.8.4.4");
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.ipregistry.co/?key=tryout",
CURLOPT_POSTFIELDS => json_encode($ips),
CURLOPT_HTTPHEADER => array('Content-Type:application/json'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CUSTOMREQUEST => "POST",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "An error occurred while retrieving IP info:" . $err;
} else {
$ipinfo = json_decode($response, true);
print_r($ipinfo['results']);
}
NodeJS (Vanilla)
const https = require('https');
https.get('https://api.ipregistry.co/?key=tryout', res => {
let payload = '';
res.on('data', data => {
payload += data;
});
res.on('end', () => {
const json = JSON.parse(payload);
console.log('Your country is ' + json['location']['country']['name']);
});
});
Python 2
import json
import urllib2
resource = urllib2.urlopen('https://api.ipregistry.co/?key=tryout')
payload = resource.read().decode('utf-8')
country = json.loads(payload)['location']['country']['name']
print('Your country is: {0}'.format(country))
Python 3
import json
import urllib.request
resource = urllib.request.urlopen('https://api.ipregistry.co/?key=tryout')
payload = resource.read().decode('utf-8')
country = json.loads(payload)['location']['country']['name']
print('Your country is: {0}'.format(country))
Ruby
require 'net/http'
require 'json'
payload = Net::HTTP.get(URI('https://api.ipregistry.co/?key=tryout'))
json = JSON.parse(payload)
puts "Your country is " + json['location']['country']['name']
Swift
import Foundation
let request = NSMutableURLRequest(url: NSURL(string: "https://api.ipregistry.co/?key=tryout")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print("An error occurred while fetching IP Info " + error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()