65.9K
CodeProject is changing. Read more.
Home

How to get the IP Address from your workstation

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.13/5 (8 votes)

Feb 16, 2002

viewsIcon

356614

How to get the IP Address from your workstation to use in your scripts

When using VBScript in a network environment you sometimes want to retrieve the IP Address to use it, for example, to retrieve the correct server from which you want to install software.

This isn't an easy task. The IP address isn't set in the environment when the computer boots, so we've got to use another method to retrieve the address.

The method which I use in the script below is reading the IP address from the CurrentControlSet in the registry. This makes sure that, even when you use DHCP, you get the right IP address.

The script contains two functions: GetIPAddress and GetIPOctet. With GetIPAddress you get an array which contains the IP address. Remember that element 0 in the array is actually the first octet of your IP address.

' Example on how to get a messagebox with the first octet of your IP Address.
wscript.echo GetIPOctet (1)

Above you find a little example which prints out the first octet of the IP address.

Here you find the complete script as it is now. Include it in your own programs at your own risk. Always be careful, since you are reading the registry.

' Script to retrieve the current IP Address on the first network card.
'
' (c) 2002 A.J. Elsinga
'      anne.jan@network-direct.com
'
'      version 1.0
 

' ************************************************************
' ***           Start of functions and procedures          ***
' ************************************************************

Function GetIPAddress
' This function retrieves the IP Address from the registry
' It gets it from the CurrentControlSet, so even when using DHCP 
' it returns the correct IP Address

' Declare variables

   Dim key
   Dim cTempIPAddress
   Dim cIPAddress
   dim cIPAddressKey


   Set oSh = CreateObject("WScript.Shell")

   cInterfacesKey="HKLM\SYSTEM\CurrentControlSet\Services\TCPIP\Parameters\Interfaces\"
   cNICSearch="HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\1\ServiceName"


' First check which network card to use
   cNicServiceName=oSh.RegRead(cNICSearch)

' Now read the IP Address from that card
   cIPAddressKey=cInterfaceskey + cNicServiceName+"\IPAddress"
   cTempIPAddress=oSh.RegRead (cIPAddresskey)
 
' Split the items in the var tempIPAddress to the octets in array IPAddress
   cIPAddress=split (cTempIPAddress(0),".",4)
 
' the IP addresss is now readable from ipaddress
' for example, to read the first octet, use: FirstOctet=IPAddress(0)
 
   GetIPAddress=cIPAddress
End Function

Function GetIPOctet (nOctet)
' This function retrieves a given octet out of the IP Address
    Dim IPAddress
   
    IPAddress=GetIPAddress
    GetIPOctet=IPAddress(nOctet-1)	
End Function