how to get country code from ip address

In this post, we will write the code to fetch and read the Country code and Country flag from ip address

For this to achieve we will be using “ip-stack” service.

Therefore, we should first register with “ip-stack” service for a free account.

The free “ip-stack” account gives us to use 10,000 request as of today.

Step-1

Thus for the purpose of this video we assume that you have already created an account with “ip-stack” and that you have your “API-key” handy with you.

Step-2: ip-stack’s response analysis

Now if we take a look at the REST api that ip-stack exposes at the below URL.

URL : http://api.ipstack.com/YOUR_IP_ADDRESS ? access_key=YOUR_ACCESS_KEY

RESPONSE: The response that we will get after calling the above GET endpoint is like below.

{
  "ip": "YOUR_IP_ADDRESS",
  "hostname": "YOUR_IP_ADDRESS",
  "type": "ipv4",
  "continent_code": "NA",
  "continent_name": "North America",
  "country_code": "US",
  "country_name": "United States",
  "region_code": "CA",
  "region_name": "California",
  "city": "Los Angeles",
  "zip": "90013",
  "latitude": 34.0453,
  "longitude": -118.2413,
  "location": {
    "geoname_id": 5368361,
    "capital": "Washington D.C.",
    "languages": [
        {
          "code": "en",
          "name": "English",
          "native": "English"
        }
    ],
    "country_flag": "https://assets.ipstack.com/images/assets/flags_svg/us.svg",
    "country_flag_emoji": "??",
    "country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
    "calling_code": "1",
    "is_eu": false
  },
  "time_zone": {
    "id": "America/Los_Angeles",
    "current_time": "2018-03-29T07:35:08-07:00",
    "gmt_offset": -25200,
    "code": "PDT",
    "is_daylight_saving": true
  },
  "currency": {
    "code": "USD",
    "name": "US Dollar",
    "plural": "US dollars",
    "symbol": "$",
    "symbol_native": "$"
  },
  "connection": {
    "asn": 25876,
    "isp": "Los Angeles Department of Water & Power"
  },
  "security": {
    "is_proxy": false,
    "proxy_type": null,
    "is_crawler": false,
    "crawler_name": null,
    "crawler_type": null,
    "is_tor": false,
    "threat_level": "low",
    "threat_types": null
  }
}

Step -3 : Java models for deserializing the response received ~

For the purpose of deserializing the response received from IP-stack endpoint, we would be creating a POJO class. Below is the code.

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.triniti.ai.model.ResponseDefaultModel;

import java.util.HashMap;
import java.util.Map;

/**
 * @author codegigs.app
 */
public class IpStackUiResponseModel{
    @JsonProperty("location")
    private LocationUi location = new LocationUi();

    @JsonProperty("location")
    public LocationUi getLocation() {
        return location;
    }

    @JsonProperty("location")
    public void setLocation(LocationUi location) {
        this.location = location;
    }

}

Another class for the LocationUi.java model .


import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 * @author codegigs.app
 */

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"country_code",
"calling_code",
"country_flag_emoji"
})
public class LocationUi {

@JsonProperty("country_code")
private String countryCode;
@JsonProperty("calling_code")
private String callingCode;
@JsonProperty("country_flag_emoji")
private String countryFlagEmoji;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("country_code")
public String getCountryCode() {
return countryCode;
}

@JsonProperty("country_code")
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}

@JsonProperty("calling_code")
public String getCallingCode() {
return callingCode;
}

@JsonProperty("calling_code")
public void setCallingCode(String callingCode) {
this.callingCode = callingCode;
}

@JsonProperty("country_flag_emoji")
public String getCountryFlagEmoji() {
return countryFlagEmoji;
}

@JsonProperty("country_flag_emoji")
public void setCountryFlagEmoji(String countryFlagEmoji) {
this.countryFlagEmoji = countryFlagEmoji;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

Step -3 : Writing a Service class

import com.fasterxml.jackson.databind.ObjectMapper;
import app.codegigs.tutorials.spring.model.ipstack.IpStackResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author codegigs.app
 */

@Service
public class IpStackServiceImpl{
  
    @Override
    public IpStackUiResponseModel getIpStack(String ipaddress) throws IpStackConnectException {
        String ipStackUrl = "URL_FROM_STEP_1";
        RestTemplate restTemplate = new RestTemplate();
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(ipStackUrl, String.class);
                if(null != response && null != response.getBody()) {
                    return IpStackResponseAdapter.adaptIpStackUiModel(new ObjectMapper().readValue(response.getBody(), IpStackResponseModel.class));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        return null;
    }
}

Step-4: Rest Controller class

In our controller class we will try to get the country code based on the IP address, and if the process fails we will send the USA’s country code by default.


@RestController
@RequestMapping(path="/api")
public class IpStackController{
	@Autowired private IpStackServiceImpl ipStackService;

        @GetMapping("/ip")
	public @ResponseBody LocationUi getIpStack(HttpServletRequest request)
	{
		IpStackUiResponseModel ipStackUiResponseModel = null;
                LocationUi locationUi = new LocationUi();
		String ipaddress = request.getHeader("X-Forwarded-For");
		if(StringUtils.isNotBlank(X_Forwarded_For_header)) {
			try {
				ipStackUiResponseModel =(ipStackService.getIpStack(X_Forwarded_For_header).getLocation());
			} catch (IpStackConnectException e) {
				locationUi.setCallingCode("+1");
				locationUi.setCountryCode("US");
				locationUi.setCountryFlagEmoji("\uD83C\uDDFA\uD83C\uDDF8");
			}
		}else{
			locationUi.setCallingCode("+1");
			locationUi.setCountryCode("US");
			locationUi.setCountryFlagEmoji("\uD83C\uDDFA\uD83C\uDDF8");
                        returnModel.setResponse(locationUi);
		}
		return locationUi;
	}
}

After performing all the above steps of we now just try to make a call to the controller endpoint /api/ip, we will be seeing a response back from the server which has the country code and Country-Flag-Emoji.

Leave a Reply

Your email address will not be published. Required fields are marked *

Doubts? WhatsApp me !