Simple API Integration In C# To Get IP Address

What is API ? And How to Consume it ?


API: Application Programing Interface provides a medium of interaction between software components. Now-a-days API programing is one of the most important component of software development.

Know more about API

API is something like URL that provides some intended data to the user. Let me explain it with some real world example.

Consider you have an account in Facebook and you want to access your friend list, status, photos through codding. Here Facebook is a total different entity which has no relation with your code(application), neither you can access Facebook's code nor its database. So how can you access those data in your FB account via your application ?

Here comes the role of API, Facebook provides an interface (URL/Graph API) that gives you all the intended details of your account, those can be used in any application. So your work is just to call the API provides by the client (here Facebook) and to use the response in your application. That's it.

In this article I will show you a simple API call process in C# to get the IP address of the device, where your application is being opened.

Here is the sample project you can download it and check.


   Download Source Code Here
   

API Integration For getting the IP address of a System in ASP.NET


The main aim of an API is to return some desired information to the user so that those can be used across any application. There are many ways in which the API gives the response to the user.

Mostly an API gives response in two formats
  • XML format
  • JSON format
 (Here I will show you a sample API call to get IP address using smart-ip.net API)

A sample example of XML response.

 <?xml version="1.0" encoding="UTF-8"?>
    <geoip>
        <source>smart-ip.net</source>
        <host>193.178.146.17</host>
        <lang>en</lang>
        <countryName>Ukraine</countryName>
        <countryCode>UA</countryCode>
        <city>Kiev</city>
        <region>Kyyivs'ka Oblast'</region>
        <latitude>50.4333</latitude>
        <longitude>30.5167</longitude>
        <timezone>Europe/Kiev</timezone>
    </geoip>
A sample example of JSON response.

  {
        "source":"smart-ip.net"
        "host":"193.178.146.17",
        "lang":"en",
        "countryName":"Ukraine",
        "countryCode":"UA",
        "city":"Kiev",
        "region":"Kyyivs'ka Oblast'",
        "latitude":50.4333,
        "longitude":30.5167,
        "timezone":"Europe/Kiev"
  }
 In this example we will consider the JSON formatted response from the API. So lets start our implementation.

Our API to get the IP details is http://smart-ip.net/geoip-json?callback=?. You can find the response like below if you click on the above link.

  ?({
      "source": "smart-ip.net",
      "host": "111.93.167.67",
      "lang": "en",
      "countryName": "India",
      "countryCode": "IN",
      "city": "Calcutta",
      "region": "West Bengal",
      "latitude": "22.5697",
      "longitude": "88.3697",
      "timezone": "Asia\/Calcutta"
  });
You can find out your IP address in the above JSON response from the API along with your location, time zone etc.

Now lets do codding to implement this in c#.

First create a class with the data members those you are expecting from the API response.

  public class ApiClass
  {
     public string host { get; set; }
     public string countryName { get; set; }
     public string city { get; set; }
  }
Here is the method to get the json response and to deserialize it.

 protected void CallAPI()
 {
     // Createa request to call the dropbox api.
     WebRequest request = WebRequest.Create(new Uri("http://smart-ip.net/geoip-json?callback=?"));
     request.Method = "GET";
     request.ContentType = "application/json";

     // Get the response.
     WebResponse response = request.GetResponse();

     // Read the response.
     string apiResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
     apiResponse = apiResponse.Replace("?(", "").Replace(");", "");

     // Deserialize the json object.
     ApiClass apiObj = new JavaScriptSerializer().Deserialize<ApiClass>(apiResponse);

     // Set the label text.
     lblIP.Text = apiObj.host;
     lblCity.Text = apiObj.city;
     lblCountry.Text = apiObj.countryName;
 }
In the above method I am creating a WebRequest object with the above API and mentioning the method and contentType.

Then get the response from the web request by calling GetResponse() method. Finally hold the response in a string and deserialize it to get the desired data.

That's it you have just learned how to call an API in C#. Download the sample source code from the above download link to see a live demo.

Happy Coding...

No comments:

Post a Comment