' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
Imports System
Imports System.Collections
Imports System.Net
Imports System.Data.SqlClient

Namespace E_Geo
    Public Class GeoLocate
        Private Const ConnStr As String = "server=ARNEPC2;Integrated Security=SSPI;database=Test"
        Private Shared con As SqlConnection
        Private Shared cache As Hashtable

        Shared Sub New()
            Dim connstrcopy As String = ConnStr
            con = New SqlConnection(connstrcopy)
            con.Open
            cache = New Hashtable
        End Sub

        Public Shared Function Locate(ByVal ip As String, ByVal tblnam As String) As String
            Dim country As String = CType(cache(ip), String)
            If country Is Nothing Then
                Dim b As Byte() = Dns.Resolve(ip).AddressList(0).GetAddressBytes
                Dim ipnum As Long = 0
                Dim i As Integer
                For i = 0 To 3
                    ipnum = (ipnum << 8) Or (b(i) And &HFF)
                Next
                SyncLock con
                    Dim sel As SqlCommand = New SqlCommand("SELECT country FROM " + tblnam + " WHERE ip1 < " + ipnum.ToString + " AND " + ipnum.ToString + " < ip2", con)
                    Dim rdr As SqlDataReader = sel.ExecuteReader
                    If rdr.Read Then
                        country = CType(rdr(0), String)
                    Else
                        country = "??"
                    End If
                    rdr.Close
                    cache.Add(ip, country)
                End SyncLock
            End If
            Return country
        End Function
    End Class 
End Namespace
