Method description
Get Country Code by IP Address.
The API "ip_info()" returns a 2-letter country code (US, UK, CN, etc.) for an IP address.
You can specify a list of IP addresses to find countries for each IP address by one API call.
Request
Data Example (GET)
https://api.cleantalk.org/?method_name=ip_info&ip=8.8.8.8
Data Processing
Necessary information about the data processing.
Required Parameters
These parameters are required.
Response
The server's response is independent of the platform.
Response example
{
"data": {
"8.8.8.8": {
"country_code": "US",
"country_name": "United States"
}
}
}
Response Explanation
- If you get the call limit, the API returns an error notice.
- The current call limit is 10 per 60 seconds.
- If you get a data elements limit in the spam_check method, API returns an error notice.
- The current data elements limit is 1000.
- The recommended timeout is no more than 180 seconds.
Code Examples
Using Wget
wget https://api.cleantalk.org/?method_name=ip_info&ip=8.8.8.8 -O output.txt
Using PHP
Backend
<?php
$response = file_get_contents("https://api.cleantalk.org/?method_name=ip_info&ip=8.8.8.8");
?>
Using Python
Backend
import json
import requests
def cleantalk_ip_info(_ip: str):
"""
Get country info of presented IP.
:param _ip:
:return dict:
"""
out = {'country_code': '', 'country_name': ''}
api_url = 'https://api.cleantalk.org?method_name=ip_info&ip=' + _ip
response = requests.get(f"{api_url}")
out['country_code'] = response.json()['data'][_ip]['country_code']
out['country_name'] = response.json()['data'][_ip]['country_name']
return out
def check_ip_is_in_countries_list(_ip: str, country_codes: list):
"""
Example how can cleantalk_ip_info could be used. Check the ip for the country code it belongs to.
:param _ip:
:param country_codes:
:return: False if no matches found, country code otherwise
"""
response = cleantalk_ip_info(_ip)
if response['country_code'] in country_codes:
return response['country_code']
return False
# Set of IP addresses to check
ip_set = ['122.23.24.25', '51.22.52.11', '164.2.1.23', '176.226.238.214', '122.182.24.25', '122.23.24.21']
# Set of country codes to check if ip belongs to
countries_set = ['JP', 'RU']
# do check
for ip in ip_set:
check_result = check_ip_is_in_countries_list(ip, countries_set)
if check_result:
print(f"{ip} belongs to {check_result}")
"""
CLI will print this:
>>122.23.24.25 belongs to JP
>>176.226.238.214 belongs to RU
>>122.23.24.21 belongs to JP
"""
Using NodeJS
NodeJS Backend
const https = require('https');
const querystring = require('querystring');
const data = {
"method_name":"ip_info",
"ip":"8.8.8.8"
};
ipInfo(data).then((response) => {
// The attribute `response` will contain API result
console.log(response);
});
function ipInfo(data) {
return new Promise((resolve, reject) => {
const options = {
method: 'GET'
};
const url = 'https://api.cleantalk.org/?' + querystring.stringify(data);
const request = https.request(url, options, result => onResponse(result, resolve, reject));
const onResponse = (result, resolve, reject) => {
const hasResponseFailed = result.status >= 400;
if (hasResponseFailed) {
reject(`Request to ${result.url} failed with HTTP ${result.status}`);
}
let responseData = '';
result.on('data', (chunk) => {
responseData += chunk;
});
result.on('end', () => {
resolve(responseData);
});
}
request.end();
request.on('error', (err) => {
reject(`Encountered an error trying to make a request: ${err.message}`);
});
});
}
Using C#
The CleanTalk team would be grateful for your possible participation in the implementation of a detailed example for this language. If you would like to take part, please contact us via plugins@cleantalk.org
Using GoLang
Backend
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
var apiUrl string = "https://api.cleantalk.org"
type IpResult struct {
CountryCode string `json:"country_code"`
CountryName string `json:"country_name"`
}
type IpInfoResultData struct {
Data map[string]IpResult `json:"data"`
ErrorMessage string `json:"error_message"`
ErrorNo uint `json:"error_no"`
}
func main() {
resultData, err := IpInfo("142.250.185.110", []string{"8.8.8.8", "2a10:6e40::1", "2605:6f80:0:d::100"})
if err != nil {
fmt.Println(err.Error())
return
}
if resultData.ErrorNo > 0 {
fmt.Println(resultData.ErrorMessage)
return
}
for i, s := range resultData.Data {
fmt.Println(i, s.CountryCode, s.CountryName)
}
}
func IpInfo(ip string, ips []string) (IpInfoResultData, error) {
var req *http.Request
var resp *http.Response
var err error
var resultData IpInfoResultData
params := url.Values{}
params.Add("method_name", "ip_info")
if ip != "" {
params.Add("ip", ip)
}
reqUrl := apiUrl + "?" + params.Encode()
if len(ips) > 0 {
postParams := url.Values{}
postParams.Add("data", strings.Join(ips, ","))
req, err = http.NewRequest(http.MethodPost, reqUrl, strings.NewReader(postParams.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
} else {
req, err = http.NewRequest(http.MethodGet, reqUrl, nil)
}
if err != nil {
log.Print(err)
}
client := &http.Client{}
resp, err = client.Do(req)
if err != nil {
return resultData, err
}
defer resp.Body.Close()
answer, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resultData, err
}
err = json.Unmarshal(answer, &resultData)
return resultData, nil
}
Related Links
Available features related to the method:
It would also be interesting
- CleanTalk Anti-Spam monitoring_services_get API MethodCleanTalk Anti-Spam "monitoring_services_get" API method description This method returns list of resources...
- CleanTalk Anti-Spam monitoring_services_add API MethodCleanTalk Anti-Spam "monitoring_services_add" API method description This method is used to add new URLs...
- Spam Check API - API Method email_check_cmsAPI Method "email_check_cms" CMS-related version of email_check This method performs short email checking...