Using VB Script to display part of an IP address

Q: How can I use VB Script to display the first 3 octets in a TCP/IP address?

A: Since IP addresses are not fixed length, you will have to count the number of separators before you can extract the octets. With that said, listed below is the sample VB Script code.

strIP = inputbox("Enter an IP Address for testing to extract the first 3 Octets:")

intLastDecimal = 1

For intCounter = 1 to 3
intLastDecimal = InStr(intLastDecimal, strIP, ".") + 1
Next

iNewLength = intLastDecimal-2
strNewIP = Left(strIP, iNewLength )
MsgBox "strNewIP=" & strNewIP

To run this code, simply copy and paste it into a flat file and name it with a .VBS extension.

For more resources on VB Scripting, please visit the following links:
http://msdn2.microsoft.com/en-us/library/3ca8tfek.aspx
http://msdn2.microsoft.com/en-us/library/ms974570.aspx
http://www.w3schools.com/vbscript/vbscript_ref_functions.asp

Comments

Mark Harr said…
Sam, much easier way than counting characters. Let me introduce you to the Split function.

Option Explicit
Dim strIP, arrIP

Do
strIP = inputbox("Enter an IP Address for testing to extract the first 3 Octets:",, strIP)
If strIP = "" Then WScript.Quit

arrIP = Split(strIP, ".")
If UBound(arrIP) < 3 Then
MsgBox "IP Address entered does not have 4 segments, please reenter the address"
Else
Exit Do
End If
Loop

MsgBox "IP: " & arrIP(0) & "." & arrIP(1) & "." & arrIP(2)
Sam Nasr said…
Like the old saying, more than 1 way to skin a cat. Thanks for your input.

Popular posts from this blog

Working with double quotes (") in VB.Net

FoxCon 2019

Sep '19 Announcements