// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections; using System.Net; using System.Data.SqlClient; namespace E_Geo { public class GeoLocate { /* START CONFIGURATION */ private const String ConnStr = "server=ARNEPC2;Integrated Security=SSPI;database=Test"; /* END CONFIGURATION */ private static SqlConnection con; private static Hashtable cache; static GeoLocate() { string connstrcopy = ConnStr; con = new SqlConnection(connstrcopy); con.Open(); cache = new Hashtable(); } public static string Locate(string ip, string tblnam) { string country = (string)cache[ip]; if(country == null) { byte[] b = Dns.Resolve(ip).AddressList[0].GetAddressBytes(); long ipnum = 0; for(int i = 0; i < 4; i++) { ipnum = (ipnum << 8) | (uint)(b[i] & 0xFF); } lock(con) { SqlCommand sel = new SqlCommand("SELECT country FROM " + tblnam + " WHERE ip1 < " + ipnum + " AND " + ipnum + " < ip2", con); SqlDataReader rdr = sel.ExecuteReader(); if(rdr.Read()) { country = (string)rdr[0]; } else { country = "??"; } rdr.Close(); cache.Add(ip, country); } } return country; } } }