Announcement

Collapse
No announcement yet.

How to Determine IP using VB Script

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to Determine IP using VB Script

    Can anyone help me on this?

    Currently i use a script to determine which group the user belongs to at logon and in turn determines which logon script should run, but i would like to (If Possible) run a script determined on the IP address assigned by DHCP. Be very handy for users with laptops travelling from office to office. Was looking through alot of WSH commands but cant find any to determine IP address.

    Can it be done?

  • #2
    Re: How to Determine IP using VB Script

    Code:
    '****************************************************************
    '  File:    getipname.vbs  (WSH for VBscript)
    '  Author:           M. Gallant    09/30/2001
    '
    '  Based on script by M. Harris & T. Lavedas:
    '  posted to: microsoft.public.scripting.vbscript  2000/07/21  
    
    '  Reads IP addresses via:
    '    ipconfig.exe  (NT4 and Win2000)
    '    winipcfg.exe  (Win95)
    '  For NT4, Win2000 resolves IP addresses to FQDN names via:
    '     nslookup.exe     (with default DNS server)
    ' 
    '****************************************************************
    'Modified 2/2/02 to just show the IP addresses - Doug Knox
    'Original script located at:  http://home.istar.ca/~neutron/wsh/IPInfo/getipname.html
    arAddresses = GetIPAddresses()
    
    info = ""
    
    for each ip in arAddresses
        info = info & ip & vbTab & vbCR
    next
    
      WScript.echo "Your IP Address is: " & info
    
    Function GetFQDN(ipaddress)
    '====
    ' Returns Fully Qualified Domain Name
    ' from reverse DNS lookup via nslookup.exe
    ' only implemented for NT4, 2000
    '====
      set sh = createobject("wscript.shell")
      set fso = createobject("scripting.filesystemobject")
      Set Env = sh.Environment("PROCESS")
    
      if Env("OS") = "Windows_NT" then
        workfile = fso.gettempname
        sh.run "%comspec% /c nslookup " & ipaddress & "  > " & workfile,0,true
       set sh = nothing
       set ts = fso.opentextfile(workfile)
       data = split(ts.readall,vbcr)
       ts.close
       set ts = nothing
       fso.deletefile workfile
       set fso = nothing
      for n = 0 to ubound(data)
        if instr(data(n),"Name") then
          parts = split(data(n),":")
            hostname= trim(cstr(parts(1)))
           Exit For
        end if
        hostname = "could not resolve IP address"
      next
        GetFQDN = hostname
      else
       set sh = nothing
       set fso = nothing
       GetFQDN = ""
      end if
    End Function
    
    
    Function GetIPAddresses()
    '=====
    ' Returns array of IP Addresses as output
    ' by ipconfig or winipcfg...
    '
    ' Win98/WinNT have ipconfig (Win95 doesn't)
    ' Win98/Win95 have winipcfg (WinNt doesn't)
    '
    ' Note: The PPP Adapter (Dial Up Adapter) is
    ' excluded if not connected (IP address will be 0.0.0.0)
    ' and included if it is connected.
    '=====
      set sh = createobject("wscript.shell")
      set fso = createobject("scripting.filesystemobject")
    
      Set Env = sh.Environment("PROCESS")
      if Env("OS") = "Windows_NT" then
        workfile = fso.gettempname
        sh.run "%comspec% /c ipconfig > " & workfile,0,true
      else
        'winipcfg in batch mode sends output to
        'filename winipcfg.out
        workfile = "winipcfg.out"
        sh.run "winipcfg /batch" ,0,true
      end if
      set sh = nothing
      set ts = fso.opentextfile(workfile)
      data = split(ts.readall,vbcr)
      ts.close
      set ts = nothing
      fso.deletefile workfile
      set fso = nothing
      arIPAddress = array()
      index = -1
      for n = 0 to ubound(data)
        if instr(data(n),"IP Address") then
          parts = split(data(n),":")
          if trim(parts(1)) <> "0.0.0.0" then
            index = index + 1
            ReDim Preserve arIPAddress(index)
            arIPAddress(index)= trim(cstr(parts(1)))
          end if
        end if
      next
      GetIPAddresses = arIPAddress
    End Function
    Last edited by tonyyeb; 12th December 2007, 15:52.
    Server 2000 MCP
    Development: ASP, ASP.Net, PHP, VB, VB.Net, MySQL, MSSQL - Check out my blog http://tonyyeb.blogspot.com

    ** Remember to give credit where credit is due and leave reputation points sigpic where appropriate **

    Comment


    • #3
      Re: How to Determine IP using VB Script

      Thanks for the quick reply,

      Having trouble running that the script below. Error Stops at first command line "arAddresses = GetIPAddresses()". Is there any part of the script i have to change to suite my setup or should it run regardless?

      Im using Windows XP Pro SP2 with Windows 2003 SP2 if thats any help. On the client system im trying this script out on im logged on with Administrative rights.

      David

      Comment


      • #4
        Re: How to Determine IP using VB Script

        Try copying the code again. It looks like my copy and paste may not have done the complete code.
        Server 2000 MCP
        Development: ASP, ASP.Net, PHP, VB, VB.Net, MySQL, MSSQL - Check out my blog http://tonyyeb.blogspot.com

        ** Remember to give credit where credit is due and leave reputation points sigpic where appropriate **

        Comment


        • #5
          Re: How to Determine IP using VB Script

          Cheers,

          Worked a dream. I still have to apply the extra "if, else, then" query between the integers of the IP address Range but for the life of me i was stuck trying to find out how to get the IP address to begin with.

          When completed will post the script up.

          Thanks for your help. Much appreciated.

          David

          Comment


          • #6
            Re: How to Determine IP using VB Script

            Great stuff, glad I could help David.

            Regards

            Chris
            Server 2000 MCP
            Development: ASP, ASP.Net, PHP, VB, VB.Net, MySQL, MSSQL - Check out my blog http://tonyyeb.blogspot.com

            ** Remember to give credit where credit is due and leave reputation points sigpic where appropriate **

            Comment


            • #7
              How to Determine IP and Run Script Based on Subnet - Complete

              All Viewers:

              SCENARIO:
              You have more than one subnet in you network. (i.e 192.168.0.0, 192.168.1.0 etc.) And you want to configure a client machine for a user depending on which subnet he/she joins.

              REASONS FOR SCRIPT:
              1. If you dont use terminal Server
              2. If you only have low speed and bandwidth between Subnets and cant synchronise large folders between servers, (i.e VPN over Broadband)
              3. Regular users using different subnets (i.e Laptops, or change of Job Positions)

              CODE: (Attached)

              ... Be Good to know if this was of any use to anyone else!
              Attached Files
              Last edited by Chin up!; 12th December 2007, 21:07.

              Comment


              • #8
                Re: How to Determine IP using VB Script

                Looks great! Good stuff David, thanks for posting your code
                Server 2000 MCP
                Development: ASP, ASP.Net, PHP, VB, VB.Net, MySQL, MSSQL - Check out my blog http://tonyyeb.blogspot.com

                ** Remember to give credit where credit is due and leave reputation points sigpic where appropriate **

                Comment


                • #9
                  Re: How to Determine IP using VB Script

                  Note that the line if instr(data(n),"IP Address") then only works on English versions of the OSs.
                  Here on Dutch computers is should be "IP-adres".

                  In the example below I made the string case insensitive and I think more language independend.

                  And, if you have all Windows XP clients or you have Windows 2000 clients with WSH 5.6 installed, then you can also use the sh.Exec method instead of sh.Run.
                  Exec returns a WshScriptExec object, which contains status and error information. This method also provides access to the standard streams of the executable, such as STDOUT, which contains the command-line output of the executable.
                  The bennefit of the Exec Method here is you don't need to write and read a workfile.

                  Just an example:
                  Code:
                  If (IPMatch("192.168.")) then
                     wscript.echo "Match!"
                  Else
                     wscript.echo "Is Not"
                  End If
                  
                  
                  Function IPMatch(strIP)
                     ' this function requires WSH 5.6, 
                     ' which comes standard on Window XP and above
                     Dim  arIPAddress() : inCnt = 0
                     With Wscript.CreateObject("Wscript.Shell")
                        Task = "ipconfig.exe"
                        Task = "%COMSPEC% /C " & Task & " |Find/i ""  IP"""
                        Set Cmd = .Exec(Task)
                     End With
                     If (IsObject(Cmd)) Then
                       Do
                         ' STDOUT
                          OutLine = Cmd.StdOut.ReadLine
                          If (OutLine <> Empty) Then 
                               ReDim Preserve arIPAddress(inCnt)
                               arIPAddress(inCnt)= CStr(Trim(Split(OutLine, ":")(1)))
                               inCnt = inCnt + 1
                          End If
                  
                         ' STDERR
                          ErrLine = Cmd.StdErr.ReadLine
                          If (ErrLine <> Empty) Then 
                               wscript.echo ErrLine
                               exit Do
                          End If
                  
                       Loop While ((Cmd.Status = WshRunning) or _
                                    (Not Cmd.StdOut.AtEndOfStream))
                     End If
                     strIPAddresses = join(arIPAddress,vbLf)
                     If CBool(Instr(strIPAddresses,  strIP )) Then
                          IPMatch = True
                     Else IPMatch = False
                     End If
                  End Function

                  An otherway to determine the IP address is reading it from the registry.
                  In your question you asked for the IP address assigned by DHCP, that information is stored in the registry.
                  Code:
                  '--------------------
                  'Determine Subnet.vbs
                  '--------------------
                  subnet = GetSubnet()
                  
                  Select Case True
                  
                   case subnet = "192.168.0.0"
                      wscript.echo "Is on subnet",subnet , " [line 1]"
                      wscript.echo "Is on subnet",subnet , " [line 2]"
                      wscript.echo "Is on subnet",subnet , " [line 3]"
                  
                   case subnet = "192.168.1.0"
                      wscript.echo "Is on subnet",subnet , " [line 1]"
                      wscript.echo "Is on subnet",subnet , " [line 2]"
                      wscript.echo "Is on subnet",subnet , " [line 3]"
                  
                  End Select
                  
                  
                  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                  Function GetSubnet()
                     'Get current IP Address assigned by DHCP 
                     '(Assumes that there is only ONE active NIC)
                     Const HKEY_LOCAL_MACHINE = &H80000002
                  
                     Set oReg=GetObject("winmgmts:" _
                        & "{impersonationLevel=impersonate}!" _
                        & "\root\default:StdRegProv")
                  
                     Set WSHShell = CreateObject("Wscript.Shell")
                  
                     strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip" _
                        & "\Parameters\Interfaces\"
                  
                     oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
                  
                     On Error Resume Next
                      '   0 if success
                      '   1 if Unable to open requested key
                      '  -1 if Unable to open requested value
                      '  -2 if Value type not supported
                  
                     For Each subkey In arrSubKeys
                  
                         DHCPAddress = WSHShell.RegRead("HKLM\" _
                             & strKeyPath & subkey & "\DhcpIPAddress")
                    
                         If DHCPAddress <> "0.0.0.0" And _
                            Left(DHCPAddress,3) <> "169" Then 
                            ActiveDHCPIPAddress = DHCPAddress    
                            ActiveDhcpSubnetMask = WSHShell.RegRead("HKLM\" _
                              & strKeyPath & subkey & "\DhcpSubnetMask")
                         End If
                     Next
                     'If the value of "IPAddress" contains a valid address 
                     'or list of addresses (to replace 0.0.0.0), it takes 
                     'precedence over the value of DhcpIPAddress.
                     'http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/33598.mspx?mfr=true
                     On Error goTo 0
                  
                     If Not ActiveDHCPIPAddress = "" _
                          And Not ActiveDhcpSubnetMask = "" Then
                     'http://www.microsoft.com/technet/prodtechnol/sms/sms2003/cpdg/plan4kv9.mspx?mfr=true
                          dim addressbytes(4)
                          dim subnetmaskbytes(4)
                          i=0 : period = 1
                          while period<>len( ActiveDHCPIPAddress ) + 2
                             prevperiod=period
                             period = instr( period+1, ActiveDHCPIPAddress, "." ) + 1
                             if period = 1 then period = len( ActiveDHCPIPAddress ) + 2
                             addressbyte = mid( ActiveDHCPIPAddress, prevperiod, _
                                period-prevperiod-1 )
                             addressbytes(i)=addressbyte
                             i=i+1
                          wend
                          
                          i=0 : period = 1
                          while period<>len( ActiveDhcpSubnetMask ) + 2
                             prevperiod=period
                             period = instr( period+1, ActiveDhcpSubnetMask, "." ) + 1
                             if period = 1 then period = len( ActiveDhcpSubnetMask ) + 2
                             subnetmaskbyte = mid( ActiveDhcpSubnetMask, prevperiod, _
                                period-prevperiod-1 )
                             subnetmaskbytes(i)=subnetmaskbyte
                             i=i+1
                          wend
                          
                          subnet=""
                                for i=0 to 3
                                 subnet = subnet & (addressbytes(i) _
                                    AND subnetmaskbytes(i)) & "."
                                next
                          GetSubnet = left( subnet, len(subnet)-1 )
                  
                  End If
                  End Function
                  ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

                  \Rems

                  This posting is provided "AS IS" with no warranties, and confers no rights.

                  __________________

                  ** Remember to give credit where credit's due **
                  and leave Reputation Points for meaningful posts

                  Comment

                  Working...
                  X