Thursday, February 15, 2007

Perform a Forward and Reverse DNS Lookup in VBScript - DNSLookup - ReverseDNSLookup - IsIP

Necessity is the mother of invention as they say. Today I had to write a couple of scripts to translate DNS names into IP addresses and vice versa. Since there is no easy way to do this in VBScript, I whipped up two (well three) quick little functions that use the nslookup command to preform the lookup using the computers default DNS name servers.

They are pretty straight forward to use, for the DNSLookup function you can pass any IP address and it will try to resolve. If it is successful it will return the fully qualified domain name. (Aliases are not returned). If it fails it will return "Failed." It also checks the string that you pass with another new function called IsIP. This function checks any string you pass to see if it qualifies as a legit IP. If it is an IP the IsIP function returns "True". If not then it returns "False".

The ReverseDNSLookup will translate a fully qualified domain name into an IP address. Or if you have DNS suffix appending turned on then it will resolve computer names that are not fully qualified. If it fails to resolve to an IP the function returns "Failed."

Function ReverseDNSLookup(sIPAddress)
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com

  If Not IsIP(sIPAddress) Then
    ReverseDNSLookup = "Failed: Invalid IP."
    Exit Function
  End If

  Const OpenAsDefault = -2
  Const FailIfNotExist = 0
  Const ForReading = 1

  Set oShell = CreateObject("WScript.Shell")
  Set oFSO = CreateObject("Scripting.FileSystemObject")
  sTemp = oShell.ExpandEnvironmentStrings("%TEMP%")
  sTempFile = sTemp & "\" & oFSO.GetTempName

  oShell.Run "%comspec% /c nslookup " & sIPAddress & ">" & sTempFile, 0, True

  Set fFile = oFSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsDefault)
  sResults = fFile.ReadAll
  fFile.Close
  oFSO.DeleteFile (sTempFile)

  If InStr(sResults, "Name:") Then
    aNameTemp = Split(sResults, "Name:")
    aName = Split(Trim(aNameTemp(1)), Chr(13))
 
    ReverseDNSLookup = aName(0)
  Else
    ReverseDNSLookup = "Failed."
  End If
 
  Set oShell = Nothing
  Set oFSO = Nothing
End Function

Function DNSLookup(sAlias)
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com

  If len(sAlias) = 0 Then
    DNSLookup = "Failed."
    Exit Function
  End If

  Const OpenAsDefault = -2
  Const FailIfNotExist = 0
  Const ForReading = 1

  Set oShell = CreateObject("WScript.Shell")
  Set oFSO = CreateObject("Scripting.FileSystemObject")
  sTemp = oShell.ExpandEnvironmentStrings("%TEMP%")
  sTempFile = sTemp & "\" & oFSO.GetTempName

  oShell.Run "%comspec% /c nslookup " & sAlias & ">" & sTempFile, 0, True

  Set fFile = oFSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsDefault)
  sResults = fFile.ReadAll
  fFile.Close
  oFSO.DeleteFile (sTempFile)

  aIP = Split(sResults, "Address:")

  If UBound(aIP) < 2 Then
    DNSLookup = "Failed."
  Else
    aIPTemp = Split(aIP(2), Chr(13))
    DNSLookup = trim(aIPTemp(0))
  End If
 
  Set oShell = Nothing
  Set oFSO = Nothing
End Function

Function IsIP(sIPAddress)
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com

  aOctets = Split(sIPAddress,".")
 
  If IsArray(aOctets) Then
    If UBound(aOctets) = 3 Then
      For Each sOctet In aOctets
        On Error Resume Next
        sOctet = Trim(sOctet)
        sOctet = sOctet + 0
        On Error Goto 0
       
        If IsNumeric(sOctet) Then
          If sOctet < 0 Or sOctet > 256 Then
            IsIP = False
            Exit Function
          End If
        Else
          IsIP = False
          Exit Function
        End If
      Next
      IsIP = True
    Else
      IsIP = False
    End If
  Else
    IsIP = False
  End If
End Function
Send this to:                          

Comments

Brian Smith said...

This is PERFECT!!!!

11/19/2007 7:40:17 AM

Roger Braithwaite said...

Jeez have you even TESTED the reverse lookup script on anything other than a few DNS names?
Try it with Google or Yahoo. They return 'Addresses:' instead of 'Address:' and so your reverse lookup script returns 'failed'!
Easily corrected, but I'll leave you to do that for other visitors to this site, perhaps it'll teach you a little bit of THOROUGHNESS in your coding practises.

2/13/2008 3:37:09 AM

Nathan Rice said...

Hey Roger,

Here's an idea. Go fuck yourself. I am sharing these for FREE for the benefit of jerkoffs like you. If you can't recognize that I share these hoping that they will help people and come with absolutely no warranty or fitness for purpose you'd get the idea. Too bad you're to fucking retarded to see that in the first place though. Good luck in your career. I can tell you'll go far.

2/13/2008 9:31:40 AM

Will said...

Thank you, this is just what the doctor ordered. =)

2/18/2008 1:15:17 PM

Will Mooar said...

May I use this for an internal script used at my workplace? Thanks

2/18/2008 1:37:43 PM

Will+Mooar said...

ps. The function names for DNSLookup and ReverseDNSLookup are the reverse of what they do. This stumped me for a couple of mins til I realised =)

ref:
http://www.techweb.com/encyclopedia/defineterm.jhtml?term=reverseDNS
http://searchcio-midmarket.techtarget.com/sDefinition/0,,sid183_gci213968,00.html
(and others)

Thanks again

2/18/2008 2:23:20 PM

Nathan+Rice said...

Feel free to use this in your place of work. However, please don't redistribute this in any kind of commercial software package. I'm glad you found it useful. :)

Thanks!

-Nate

2/18/2008 4:03:40 PM

Johan said...

Thank you very much for your script. It worked like a charm and saved me a bunch of time writing something not even half as good!

--Johan

3/12/2008 11:19:52 AM

Magnus said...

I'd suggest adding "Exit Function"s to the checks at the top of each lookup function. It does not make alot of sense to try and lookup an empty string or an invalid ip address.

4/18/2008 7:13:17 AM

said...

Here is a way to improve on this by not using temporary text files and using WshScriptExec Objects instead:


Function DNSLookup(sAlias)
Dim objShell, objExec, sResults, aIPTemp
Dim aIP

Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("nslookup " & sAlias)

Do Until objExec.Status = 1

WScript.Sleep 100

Loop

sResults = objExec.StdOut.Readall

''wscript.echo sResults

aIP = Split(sResults, "Address:")

If UBound(aIP) < 2 Then
DNSLookup = "Failed."
Else
aIPTemp = Split(aIP(2), Chr(13))
DNSLookup = trim(aIPTemp(0))
End If

Set objExec = Nothing
Set objShell = Nothing
End Function

7/2/2008 12:09:54 PM

said...

Hi Nat. Your script rocks. Thank you for sharing your hard work out. I would like to use it at work to set proxy based on location. Would you agree to this. It will not be sold or distributed to individuals outside the organisation and I will keep your credits on my script.

8/7/2008 3:05:01 AM

said...

One small change - the ''>256'' s/b ''>255''.

12/9/2008 12:47:51 PM

said...

Jeez, you could have come round to my work place and done the actual spreadsheet I need to produce. I''ll leave that for you to do another time though. Slacker! ;)

very useful thanks, will save me plenty of time.

Matt



4/20/2009 8:34:01 AM

said...

I was looking for a script like this for a long time, after a long search I found this script.

But here''s the problem - I only know HTML, Javascript and PHP language. Can anyone give me step-by-step instructions on how to successfully upload the file on the server. Help will be greatly appreciated. Please HELP!!

5/8/2009 8:39:39 AM

said...

Excellent!!! MANY BIG THANKS! This is exactly what i needed. I was creating vbs cript for BGInfo to show some things about DNS and IP, and this really rocks!
Thank you very much.
And for Roger: go fuck yourself motherfucker!

7/28/2009 6:45:07 AM

said...

Kudos Nate. Getting an the primary IP from WMI can be a pain and this is a nice alternative.

PS. Roger can go get fucked, or suck a big one; whatever shitheads like him do.

4/6/2011 7:57:01 AM

said...

Here is the question, how about we need to run this Script in different Culture in different languages. How one can use this Script.
Thanks

11/18/2011 1:42:24 PM

Name
URL
Email
Email address is not published
Remember Me
Comments

CAPTCHA
Write the characters in the image above