Skip to main content

Geolocation using ip address

Here is a method for C-sharp lovers, It will fetch the IP Address of Client and some other browser info of the host when you run it after compiling your code.

We are just creating Http Request and an object of HttpBrowserCapabilities class. Now with this object we can collect all the host specific data that we will send to service to get the Geolocation of the host.

private string UserLogEntry(string flag)
    {
        String publicIpAddress = HttpContext.Current.Request.UserHostAddress.ToString();
        HttpBrowserCapabilities oBrowserCap = Request.Browser;
        String browserName = oBrowserCap.Browser.ToString();
        String version =  oBrowserCap.Version.ToString();
        String majorVersion =oBrowserCap.MajorVersion.ToString();
        String minorVersion =oBrowserCap.MinorVersion.ToString();
        String platform = oBrowserCap.Platform.ToString();
        String isBeta = oBrowserCap.Beta.ToString();
        String isCrawler =oBrowserCap.Crawler.ToString();
        String isAOL = oBrowserCap.AOL.ToString();
        String location = "";
        String ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
        
String[] responseArray = GetLocation(publicIpAddress);
            if (responseArray[0].Equals("ERROR"))
            {
                //there is an error in response from service
            }
            else if (responseArray[0].Equals("OK"))
            {
                location = responseArray[6] + '-' + responseArray[5] + '-' + responseArray[4]; 
                //[0]-successFlag [1]-nahi pata, [2]-ip, [3]-country abbrivieted, [4]-country fullname, [5]-State, [6]-city, [7]-zip, [8]-lat, [9]-long, [10]- pata nahi
            }
        

        string msg = (string)SqlHelper.ExecuteScalar(Config.XcatLinkAccountDB, "spInsertUpdateLog", Convert.ToInt32(Session["LoginUserId"]), Convert.ToString(Session.SessionID), publicIpAddress, DBNull.Value, location, browserName + ' ' + version, DBNull.Value, DBNull.Value, flag);
        return msg;
    }
// then here is a method that is used in above method to get the location of that IP Address
private String[] GetLocation(string ipaddress)
    {

        // here is the API Key: 2000cf96f94f92711724080f77d60246ff9e5eaac83d14076a1fb090346e3a8c
        // User Id : s******.acs@gmail.com 
        // :)
        try
        {
            String responseString;
            String[] responseArray = new String[20];
            responseArray[0] = "ERROR";
                
            if (ipaddress != "127.0.0.1")
            {
                var webClient = new WebClient();
                responseString = webClient.DownloadString(String.Format("http://api.ipinfodb.com/v3/ip-city/?key=2000cf96f94f92711724080f77d60246ff9e5eaac83d14076a1fb090346e3a8c&ip=" + ipaddress));
// OUTPUT                
// the result is "OK;;183.182.87.10;IN;INDIA;MADHYA PRADESH;INDORE;-;22.7186;75.8558;+05:30"
                responseArray = responseString.Split(';');
                // or we can use http://api.hostip.info/?ip='' , this will return a xml file and then go for xmlReader

}
            return responseArray;
        }
        catch (Exception ex)
        {
            throw ex;
            //Response.Write(ex.Message);
        }
    }



This geolocation can be written in other server side languages like PHP/JAVA etc, using the same service. Developer can decide at the time that he/she wants a text or xml response from the service.

The xml response using above code would look like this:
geolocation by ip address



While using ipinfodb api in C#, we have to convert the response in string through webclient

String responseString = webClient.DownloadString(String.Format("http://api.ipinfodb.com/v3/ip-city/?key=2000cf96f94f92711724080f77d60246ff9e5eaac83d14076a1fb090346e3a8c&ip=" + ipaddress));


OR

Use http://api.hostip.info/?ip='' , this will return a xml file and then go for xmlReader




FOR Javascript/ JSON lovers here is the code:

IP Address Geolocation JSON API The API returns the location of an IP address (country, region, city, zipcode, latitude and longitude) and the associated timezone in JSON format. Usage
For city precision, simply do a query at this address (if you omit the IP parameter it will check with your own IP) : http://api.ipinfodb.com/v3/ip-city/?key=&ip=74.125.45.100&format=json
For country precision (faster), simply do a query with the following API : http://api.ipinfodb.com/v3/ip-country/?key=&ip=74.125.45.100&format=json


Output
This is a sample of the output you will get in JSON with city precision :

{
 "statusCode" : "OK",
 "statusMessage" : "",
 "ipAddress" : "74.125.45.100",
 "countryCode" : "US",
 "countryName" : "UNITED STATES",
 "regionName" : "CALIFORNIA",
 "cityName" : "MOUNTAIN VIEW",
 "zipCode" : "94043",
 "latitude" : "37.3956",
 "longitude" : "-122.076",
 "timeZone" : "-08:00"
}


for API KEY and more documentation links:

Registration : http://ipinfodb.com/register.php
Description: http://ipinfodb.com/ip_location_api.php
All the courtesy : http://ipinfodb.com/

What's Hot

CVR Nummer : Register CVR Number for Denmark Generate and Test Online

CVR Nummer : Register CVR Number for Denmark Generate and Test Online | Image credit: Pexel What Is Danish CVR The Central Business Register (CVR) is the central register of the state with information on all Danish companies. Since 1999, the Central Business Register has been the authoritative register for current and historical basic data on all registered companies in Denmark. Data comes from the companies' own registrations on Virk Report. There is also information on associations and public authorities in the CVR. As of 2018, CVR also contains information on Greenlandic companies, associations and authorities. In CVR at Virk you can do single lookups, filtered searches, create extracts and subscriptions, and retrieve a wide range of company documents and transcripts. Generate Danish CVR For Test (Fake) Click the button below to generate the valid CVR number for Denmark. You can click multiple times to generate several numbers. These numbers can be used to Test your ...

Bing Homepage Quiz: Fun, Win Rewards, and Brain Teasers

Bing, Microsoft's search engine, has taken interactive engagement to the next level with its captivating feature - the Bing Homepage Quiz. This intriguing daily quiz not only challenges your knowledge but also offers a chance to earn rewards. In this comprehensive guide, we will explore the ins and outs of the Bing Homepage Quiz, including how to play, the different types of quizzes, and how you can earn and use rewards through this engaging feature. Bing homepage Quiz | Image credit: LanguageLassi How to Play the Bing Homepage Quiz Playing the Bing Homepage Quiz is simple and enjoyable. Here's how you can get started: Visit Bing : Open your preferred web browser and navigate to the Bing homepage (bing.com). Look for the Quiz : On the Bing homepage, keep an eye out for the interactive quiz card. This card is usually located near the bottom of the page and features a captivating image related to the quiz. Click to Start : Click on the quiz card to begin the quiz. It...

How To Iterate Dictionary Object

Dictionary is a object that can store values in Key-Value pair. its just like a list, the only difference is: List can be iterate using index(0-n) but not the Dictionary . Generally when we try to iterate the dictionary we get below error: " Collection was modified; enumeration operation may not execute. " So How to parse a dictionary and modify its values?? To iterate dictionary we must loop through it's keys or key - value pair. Using keys