如何获取工作站的 IP 地址






3.13/5 (8投票s)
2002 年 2 月 16 日

357326
如何获取工作站的 IP 地址以在您的脚本中使用。
在网络环境中,当使用 VBScript 时,您有时需要获取 IP 地址,例如为了从您想要安装软件的正确服务器获取地址。
这并非易事。计算机启动时,IP 地址并未在环境中设置,因此我们需要使用另一种方法来获取地址。
我在下面的脚本中使用的方法是从注册表中的 CurrentControlSet
读取 IP 地址。这确保了即使您使用 DHCP,也能获得正确的 IP 地址。
该脚本包含两个函数:GetIPAddress
和 GetIPOctet
。使用 GetIPAddress
可以获得包含 IP 地址的数组。请记住,数组中的元素 0 实际上是您的 IP 地址的第一个八位字节。
' Example on how to get a messagebox with the first octet of your IP Address.
wscript.echo GetIPOctet (1)
在上面,您会找到一个示例,它会打印出 IP 地址的第一个八位字节。
以下是完整的脚本。请自行承担风险将其包含在您自己的程序中。务必小心,因为您正在读取注册表。
' 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