Mini cache dns

Soyez le premier à donner votre avis sur cette source.

Snippet vu 21 526 fois - Téléchargée 15 fois

Contenu du snippet

Mini Cache DNS à utilisation simple. Fonctionne très bien pour des caches de taille moyennes (je pense +/- 50 à 75 noms)

Utilisez-le via la fonction automatique : DNSRequest(ByVal host As String) As Net.IPAddress

(Le module de log n'est pas de moi)

Source / Exemple :


Class clsDNSCache
    Structure DNSCacheDataType
        Dim DomainName As String
        Dim IP As Net.IPAddress
        Dim datetime As DateTime

        Sub Parse(ByVal Entry As String)
            Dim tmp() As String = Split(Entry, ":")
            DomainName = tmp(0)
            IP = Net.IPAddress.Parse(tmp(1))
            datetime = Date.FromBinary(tmp(2))
        End Sub
        Overrides Function ToString() As String
            Return DomainName & ":" & IP.ToString & ":" & datetime.ToBinary
        End Function

        Shared Empty As New DNSCacheDataType
    End Structure

    Dim Data As New ArrayList
    Dim filename As String = My.Application.Info.DirectoryPath & "\DNSCache.dat"
    Dim file As New IO.FileStream(filename, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.Read)

    Public Sub New()
        Log.WriteToLog("dnscache.log", "Initializing DNSCache")
        Dim filereader As New IO.StreamReader(file)
        Do Until filereader.EndOfStream
            Dim newentry As New DNSCacheDataType
            newentry.Parse(filereader.ReadLine())
            Data.Add(newentry)
        Loop
        filereader.Close()
        Log.WriteToLog("dnscache.log", "DNSCache initialized")
        CleanExpired()
    End Sub

    Public Function Read(ByVal DomainName As String) As DNSCacheDataType
        Log.WriteToLog("dnscache.log", "Searching entry DN=" & DomainName)
        CleanExpired()
        For Each entry As DNSCacheDataType In Data
            If entry.DomainName = DomainName Then
                Log.WriteToLog("dnscache.log", "Entry found : DN=" & entry.DomainName & " IP=" & entry.IP.ToString & " Date=" & entry.datetime.ToShortDateString & " " & entry.datetime.ToShortTimeString)
                Return entry
            End If
        Next
        Log.WriteToLog("dnscache.log", "Entry not found")
        Return DNSCacheDataType.Empty
    End Function
    Public Function Read(ByVal IP As Net.IPAddress) As DNSCacheDataType
        Log.WriteToLog("dnscache.log", "Searching entry IP=" & IP.ToString)
        CleanExpired()
        For Each entry As DNSCacheDataType In Data
            If entry.IP.Equals(IP) Then
                Log.WriteToLog("dnscache.log", "Entry found : DN=" & entry.DomainName & " IP=" & entry.IP.ToString & " Date=" & entry.datetime.ToShortDateString & " " & entry.datetime.ToShortTimeString)
                Return entry
            End If
        Next
        Log.WriteToLog("dnscache.log", "Entry not found")
        Return DNSCacheDataType.Empty
    End Function
    Public Sub Write(ByVal DomainName As String, ByVal IP As Net.IPAddress)
        Log.WriteToLog("dnscache.log", "Writing new entry : DN=" & DomainName & " IP=" & IP.ToString)
        Dim entry As New DNSCacheDataType
        entry.DomainName = DomainName
        entry.IP = IP
        entry.datetime = DateTime.Now
        Data.Add(entry)
        Log.WriteToLog("dnscache.log", "New entry writed")
        FlushToDisk(False)
    End Sub
    Public Sub CleanExpired(Optional ByVal hours As Double = 2)
        Log.WriteToLog("dnscache.log", "Cleaning expired entries")
restart:
        For Each entry As DNSCacheDataType In Data
            If entry.datetime.AddHours(hours) < Now Then
                Log.WriteToLog("dnscache.log", "Deleting : DN=" & entry.DomainName & " IP=" & entry.IP.ToString)
                Data.Remove(entry)
                GoTo restart
            End If
        Next
        Log.WriteToLog("dnscache.log", "Expired entries deleted")
        FlushToDisk(False)
    End Sub
    Public Sub Clear(Optional ByVal NeedToLog As Boolean = True)
        If NeedToLog Then Log.WriteToLog("dnscache.log", "Clearing DNSCache")
        file.Close()
        IO.File.Delete(filename)
        file = New IO.FileStream(filename, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, IO.FileShare.Read)
        If NeedToLog Then Log.WriteToLog("dnscache.log", "DNSCache cleared")
    End Sub
    Public Sub FlushToDisk(Optional ByVal NeedToLog As Boolean = True)
        If NeedToLog Then Log.WriteToLog("dnscache.log", "Writing DNSCache database")
        Clear(False)

        Dim filewriter As New IO.StreamWriter(file)
        For Each entry As DNSCacheDataType In Data
            filewriter.WriteLine(entry.ToString)
        Next
        filewriter.Close()
        If NeedToLog Then Log.WriteToLog("dnscache.log", "DNSCache database writed")
    End Sub

    Public Function DNSRequest(ByVal host As String) As Net.IPAddress
        Dim entry As clsDNSCache.DNSCacheDataType = Read(host)
        If entry.Equals(clsDNSCache.DNSCacheDataType.Empty) Then
            WriteToLog("dnscache.log", "Resolving : " & host)
            DNSRequest = Net.Dns.GetHostEntry(host).AddressList(0)
            WriteToLog("dnscache.log", " => Resolved : " & DNSRequest.ToString)
            Write(host, DNSRequest)
        Else
            DNSRequest = entry.IP
        End If
    End Function
End Class

Module Log
    Public Sub WriteToLog(ByVal Filename As String, ByVal Comment As String)
        Dim sw As System.IO.StreamWriter
        Try
            Console.WriteLine(Comment)
            sw = New System.IO.StreamWriter(Filename, True)
            sw.WriteLine(Date.Now & "     " & Comment)
        Catch e As Exception
        Finally
            If Not sw Is Nothing Then sw.Close()
        End Try
    End Sub
End Module

Conclusion :


Nécessite une petite optimisation pour des gros cache : ne pas effectuer le FlushToDisk à chaque modifications en mémoire

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.