VB.Net - Simple Function to do an nslookup


This is just a simple example function that will return a string with some DNS lookup information for an ip address or host name. You may need to import System.Text and System.Net if they’re not imported and you have compile errors. I believe this only works for DNS A records. If you need something more in depth to look at DNS SRV records then you may need to look at using the Windows API (specifically look for “dnsapi” library calls). If I can remember I’ll try to post an example using that in the near future.

Protected Shared Function DnsLookup(ByVal hostNameOrAddress As String) As String
    Dim sb As New StringBuilder
    sb.AppendFormat("Lookup: {0}{1}", hostNameOrAddress, vbCrLf)

    Dim hostEntry As IPHostEntry = Dns.GetHostEntry(hostNameOrAddress)
    sb.AppendFormat("  Host Name: {0}{1}", hostEntry.HostName, vbCrLf)
    
    Dim ipAddresses As IPAddress() = hostEntry.AddressList
    
    For Each ip As IPAddress In ipAddresses
        sb.AppendFormat("  IP Address: {0}{1}", ip, vbCrLf)
    Next

    Return sb.ToString
End Function