Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

Get City/State/Country From IP

Posted on September 27, 2013October 26, 2015 By David Kittell

I have a lot of possible options on this page, as I find time I’ll clean this page
up a bit to make it more user friendly.

C# Free, Fast
JavaScript Free, Fast
Microsoft SQL

Using GeoPlugin.net XML Option

[raw]

All Values

geoPlugin:
geoplugin_request: 208.67.222.222
geoplugin_status: 200
geoplugin_credit: Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.
geoplugin_city: San Francisco
geoplugin_region: CA
geoplugin_areaCode: 415
geoplugin_dmaCode: 807
geoplugin_countryCode: US
geoplugin_countryName: United States
geoplugin_continentCode: NA
geoplugin_latitude: 37.769699
geoplugin_longitude: -122.393303
geoplugin_regionCode: CA
geoplugin_regionName: California
geoplugin_currencyCode: USD
geoplugin_currencySymbol: $
geoplugin_currencySymbol_UTF8: $
geoplugin_currencyConverter: 1

Specific Values

City, State: San Francisco, CA

Latitude, Longitude: 37.769699, -122.393303

[/raw]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Xml;

public partial class IPtoCityXML : System.Web.UI.Page
{
	//public static string sTestIP = "208.67.222.222";
	public static string sTestIP =  IpAddress();

	protected void Page_Load(object sender, EventArgs e)
	{
		#region Display All Values
		Response.Write("<h1>All Values</h1>");
		sGetAllDetails(sTestIP);
		#endregion Display All Values

		#region Display Specific Values
		Response.Write("<h1>Specific Values</h1>");
		Response.Write("<p><strong>City, State:</strong> " + sGetSpecificInformation(sTestIP, 1) + ", " + sGetSpecificInformation(sTestIP, 2) + "</p>");
		Response.Write("<p><strong>Latitude, Longitude:</strong> " + sGetSpecificInformation(sTestIP, 4) + ", " + sGetSpecificInformation(sTestIP, 5) + "</p>");
		#endregion Display Specific Values
	}

	private string IpAddress()
	{
		string strIpAddress;
		strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
		if (strIpAddress == null)
			strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
		return strIpAddress;
	}

	public void sGetAllDetails(string sIPAddress)
	{
		System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("http://www.geoplugin.net/xml.gp?ip=" + sIPAddress);
		string sContents = "";
		while (reader.Read())
		{
			reader.MoveToContent();
			if (reader.NodeType == System.Xml.XmlNodeType.Element)
				sContents += reader.Name + ": <" + reader.Name + "> ";
			if (reader.NodeType == System.Xml.XmlNodeType.Text)
				sContents += reader.Value + "<br/>";
		}

		Response.Write(sContents);
	}

	public string sGetSpecificInformation(string sIPAddress, int nOption)
	{
		string sContents = "";
		string sXMLElement = "";

		System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

		doc.Load("http://www.geoplugin.net/xml.gp?ip=" + sIPAddress);

		switch (nOption)
		{
			case 1:
				sXMLElement = "geoplugin_city";
				break;
			case 2:
				sXMLElement = "geoplugin_region";
				break;
			case 3:
				sXMLElement = "geoplugin_countryName";
				break;
			case 4:
				sXMLElement = "geoplugin_latitude";
				break;
			case 5:
				sXMLElement = "geoplugin_longitude";
				break;
		}

		System.Xml.XmlElement root = doc.DocumentElement;
		System.Xml.XmlNodeList lst = root.GetElementsByTagName(sXMLElement);
		foreach (System.Xml.XmlNode n in lst)
		{
			sContents += n.InnerText;
		}
		return sContents;
	}
}

Using MaxMind.com JavaScript Option

[raw]

City
Region
Region Name
Postal Code
Country Code
Country Name
Latitude
Longitude

[/raw]
This website uses GeoIP2 JavaScript from MaxMind.

<script type="text/javascript" src="//j.maxmind.com/js/geoip.js">
  </script>
  <dl>

    <dt>City</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_city());
      </script>
    </dd>

    <dt>Region</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_region());
      </script>
    </dd>

    <dt>Region Name</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_region_name());
      </script>
    </dd>

    <dt>Postal Code</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_postal_code());
      </script>
    </dd>

    <dt>Country Code</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_country_code());
      </script>
    </dd>

    <dt>Country Name</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_country_name());
      </script>
    </dd>

    <dt>Latitude</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_latitude());
      </script>
    </dd>

    <dt>Longitude</dt>
    <dd>
      <script type="text/javascript">
      	document.write(geoip_longitude());
      </script>
    </dd>

  </dl>

Using MaxMind.com SQL Option

You can use the database or the web service, the code below requires the CSV from http://dev.maxmind.com/geoip/legacy/geolite/

Once you have downloaded the CSV, import it into your MSSQL database.

Once you have the database tables created you can follow the logic below

-- IP 8.8.8.8
-- (16777216 * o1) + (65536 * o2) + (256 * o3) + o4
-- (16777216 * 8) + (65536 * 8) + (256 * 8) + 8 = 134744072

--integer_ip = 2921648058
--o1 = int ( ipnum / 16777216 ) % 256;
--o2 = int ( ipnum / 65536    ) % 256;
--o3 = int ( ipnum / 256      ) % 256;
--o4 = int ( ipnum            ) % 256;
--address = ( o1, o2, o3, o4 ).join('.')

SELECT TOP 1 glcl.locId
	,startIpNum
	,endIpNum
	,country
	,region
	,city
	,postalCode
	,latitude
	,longitude
	,metroCode
	,areaCode
FROM [GeoLiteCity-Location] glcl
INNER JOIN [GeoLiteCity-Blocks] glcb ON glcl.locId = glcb.locId
WHERE '134744072' BETWEEN startIpNum
		AND endIpNum

-- OR

SELECT (city + ', ' + ltrim(isnull(region, '') + ' ' + isnull(postalCode, '')))
FROM [GeoCityLocation] glcl
INNER JOIN [GeoCityBlocks] glcb ON glcl.locId = glcb.locId
WHERE '1817375425' BETWEEN startIpNum
		AND endIpNum
CREATE FUNCTION dbo.IPAddressToInteger (@IP AS VARCHAR(15))
RETURNS BIGINT
AS
BEGIN
	RETURN (CONVERT(BIGINT, PARSENAME(@IP, 1)) + CONVERT(BIGINT, PARSENAME(@IP, 2)) * 256 + CONVERT(BIGINT, PARSENAME(@IP, 3)) * 65536 + CONVERT(BIGINT, PARSENAME(@IP, 4)) * 16777216)
END
GO
CREATE FUNCTION dbo.IntegerToIPAddress (@IP AS BIGINT)
RETURNS VARCHAR(15)
AS
BEGIN
	DECLARE @Octet1 TINYINT
	DECLARE @Octet2 TINYINT
	DECLARE @Octet3 TINYINT
	DECLARE @Octet4 TINYINT
	DECLARE @RestOfIP BIGINT

	SET @Octet1 = @IP / 16777216
	SET @RestOfIP = @IP - (@Octet1 * 16777216)
	SET @Octet2 = @RestOfIP / 65536
	SET @RestOfIP = @RestOfIP - (@Octet2 * 65536)
	SET @Octet3 = @RestOfIP / 256
	SET @Octet4 = @RestOfIP - (@Octet3 * 256)

	RETURN (CONVERT(VARCHAR, @Octet1) + '.' + CONVERT(VARCHAR, @Octet2) + '.' + CONVERT(VARCHAR, @Octet3) + '.' + CONVERT(VARCHAR, @Octet4))
END
GO

To simplify the calculation of IP into Integer use this function

public string sIPToInteger(string sIP)
	{
		string[] sIPArray = sIP.Split('.');
		return (
			(16777216 * Int32.Parse(sIPArray[0]))
			+
			(65536 * Int32.Parse(sIPArray[1]))
			+
			(256 * Int32.Parse(sIPArray[2]))
			+
			Int32.Parse(sIPArray[3])
		).ToString();
	}

Call to the function above with

Response.Write(sIPToInteger("8.8.8.8"));

While I currently do not have a reason to reverse the conversion I have created a function for that as well with below

public string sIntegerToIP(int nIPInt)
	{
		string o1, o2, o3, o4;
		o1 = ((nIPInt / 16777216) % 256).ToString();
		o2 = ((nIPInt / 65536) % 256).ToString();
		o3 = ((nIPInt / 256) % 256).ToString();
		o4 = ((nIPInt) % 256).ToString();

		return o1 + '.' + o2 + '.' + o3 + '.' + o4;
	}

Call to the function above with

Response.Write(sIntegerToIP(134744072));

Complete source code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MSR : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		Response.Write(sIPToInteger("8.8.8.8"));
		Response.Write("<p>" + sIntegerToIP(Int32.Parse(sIPToInteger("8.8.8.8"))));
	}

	public string sIPToInteger(string sIP)
	{
		string[] sIPArray = sIP.Split('.');
		return (
			(16777216 * Int32.Parse(sIPArray[0]))
			+
			(65536 * Int32.Parse(sIPArray[1]))
			+
			(256 * Int32.Parse(sIPArray[2]))
			+
			Int32.Parse(sIPArray[3])
		).ToString();
	}

	public string sIntegerToIP(int nIPInt)
	{
		string o1, o2, o3, o4;
		o1 = ((nIPInt / 16777216) % 256).ToString();
		o2 = ((nIPInt / 65536) % 256).ToString();
		o3 = ((nIPInt / 256) % 256).ToString();
		o4 = ((nIPInt) % 256).ToString();

		return o1 + '.' + o2 + '.' + o3 + '.' + o4;
	}
}

Sources:

  • http://dev.maxmind.com/geoip/legacy/geolite/
  • http://sqlblog.com/blogs/denis_gobo/archive/2008/10/05/9266.aspx
  • http://www.geoplugin.com/
Originally Posted on September 27, 2013
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

C# ASPX Code CSharp JavaScript

Post navigation

Previous post
Next post

Related Posts

Mac OSX Terminal – Change/Set DNS

Posted on May 27, 2016June 4, 2020

This may need to change depending on your network interface Manual Process # Only friendly names networksetup -listallnetworkservices # Useful information networksetup -listallhardwareports Running the above will display something like this An asterisk (*) denotes that a network service is disabled. Ethernet FireWire Wi-Fi Bluetooth PAN Thunderbolt Bridge # Optional…

Read More

Count/Limit characters in a textbox using Javascript

Posted on July 15, 2013October 26, 2015

<html> <head> <script type="text/javascript" src="/js/jquery-1.9.1.js"></script> <script type="text/javascript" src="/js/jquery.limit2.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#text").limita({ limit: 100, id_result: "counter", alertClass: "alert" }); }); </script> </head> <body> <form id="input_form" method="POST" action="?"> <textarea id="text" rows="4" cols="49"></textarea> <input type="submit" value="submit"> </form> <div id="counter"></div> </body> </html> (function($){ $.fn.limita = function(options) { var defaults = { limit:…

Read More

Ektron Find Replace In Menu

Posted on October 23, 2013October 26, 2015

This script will rename menu link paths SET XACT_ABORT ON DECLARE @currval NVARCHAR(500) DECLARE @newval NVARCHAR(500) DECLARE @search NVARCHAR(500) DECLARE @replace VARCHAR(500) SET @search = ” –string to find SET @replace = ” –replacement string DECLARE @pos INT DECLARE @id BIGINT BEGIN TRAN DECLARE curs CURSOR LOCAL FAST_FORWARD FOR SELECT…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes