get local IPv4 of computer using VB.net - vb.net

I'm trying to get the ip address of my local PC, and one one of my other PCs it gets the v4 address fine, but on this one the code:
Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString()
returns what I guess is a IPv6 address:
fe80::9c09:e2e:4736:4c62%11
How do I get the IPv4 address?

Disclaimer- I don't have IPv6 installed and there is probably a much better way to do this, but what does the following return:
Dns.GetHostEntry(Dns.GetHostName()).AddressList
.Where(a => !a.IsIPv6LinkLocal && !a.IsIPv6Multicast && !a.IsIPv6SiteLocal)
.First()
.ToString();
Edit - didn't notice you were asking in VB, so I've tried translating it to:
Dim s As String = Dns.GetHostEntry(Dns.GetHostName()).AddressList _
.Where(Function(a As IPAddress) Not a.IsIPv6LinkLocal AndAlso Not a.IsIPv6Multicast AndAlso Not a.IsIPv6SiteLocal) _
.First() _
.ToString()
This may blow up, so don't treat it as production code.

Here's my solution for getting a routable IPv4 IP without using an external service:
Function GetLocalIP() As String
Dim IPList As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
For Each IPaddress In IPList.AddressList
'Only return IPv4 routable IPs
If (IPaddress.AddressFamily = Sockets.AddressFamily.InterNetwork) AndAlso (Not IsPrivateIP(IPaddress.ToString)) Then
Return IPaddress.ToString
End If
Next
Return ""
End Function
Function IsPrivateIP(ByVal CheckIP As String) As Boolean
Dim Quad1, Quad2 As Integer
Quad1 = CInt(CheckIP.Substring(0, CheckIP.IndexOf(".")))
Quad2 = CInt(CheckIP.Substring(CheckIP.IndexOf(".") + 1).Substring(0, CheckIP.IndexOf(".")))
Select Case Quad1
Case 10
Return True
Case 172
If Quad2 >= 16 And Quad2 <= 31 Then Return True
Case 192
If Quad2 = 168 Then Return True
End Select
Return False
End Function
Note that my code is also verifying that the range is routable (IsPrivateIP). You can remove or modify that part if you are looking for something else.

I used a combined Cmd/Visual Basic code and it worked :
Dim ResString As String = "result.txt"
If File.Exists("result.txt") Then
File.Delete("result.txt")
End If
Shell("cmd.exe /c cd " & Application.StartupPath & " && ipconfig >> " & ResString & "&& exit", AppWinStyle.NormalFocus)
Dim Ipv4 As String
Dim Ipv4Found As Boolean = False
Dim Ipv4Char As Integer = 43
Dim Ipv4Str As String
Threading.Thread.Sleep(1500)
'Wait some seconds to create "result.txt"
Dim Ipv4Reader As StreamReader
Ipv4Reader = File.OpenText("result.txt")
Do Until Ipv4Found = True
Ipv4Str = Ipv4Reader.ReadLine()
If Not Ipv4Str = Nothing Then
If Ipv4Str.Contains("IPv4") Then
Try
Ipv4 = Ipv4Str.Chars(Ipv4Char)
Do Until Ipv4Char = 60
Ipv4Char = Ipv4Char + 1
Ipv4 = Ipv4 & Ipv4Str.Chars(Ipv4Char)
'Read results step by step
Loop
Catch ex As Exception
End Try
MsgBox("Your IPv4 Address is " & Ipv4)
Ipv4Found = True
Ipv4Reader.Close()
End If
Else
End If
Loop
If your computer language is english you may have some unusual characters in the IPv4 String ( My pc is actually in Italian )

I think you should use this:
Dim tmpHostName As String = System.Net.Dns.GetHostName()
myIPaddress = System.Net.Dns.GetHostByName(tmpHostName).AddressList(0).ToString()
GetHostByName is obsolete but this is the way to get the IPv4. Why? Because the getbyhostname function is created before IPv6 so the function get only the IPv4 connection, not the fe80::9c09:e2e:4736:4c62%11.

Something maybe fun is this little function that'll show all IP addresses on your computer:
Public Function getOwnIp() As String
Dim hostIP As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim position As Integer = 0
Dim ip As String = Nothing
While ipList < hostIP.AddressList.Length
ip += hostIP.AddressList(position).ToString & vbCrLf
position += 1
End While`enter code here`
Return ip
End Function

I was looking for the answer to this question myself and I could not find one suitable to my needs. I managed to experiment with various answers across the net until I came up with this (works great!). Just thought I would share since this post is the top result via Google.
''''Routine to fetch IPv4 Network addresses for all local network interfaces.
Dim adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
Dim adapter As NetworkInterface
For Each adapter In adapters
Dim properties As IPInterfaceProperties = adapter.GetIPProperties()
If properties.UnicastAddresses.Count > 0 Then
For Each unicastadress As UnicastIPAddressInformation In properties.UnicastAddresses
Dim ip As IPAddress = unicastadress.Address
If ip.AddressFamily = AddressFamily.InterNetwork Then
ComboBox1.Items.Add(ip.ToString)
End If
Next unicastadress
End If
Next adapter

You first need to import the system namespace into your application and then create an instance of the System.Net.NetworkInformation.IPAddressInformation and use it as such
Example
Imports system.data.sqlclient
imports system
Public class Form1
Dim IPAdd As System.Net.NetworkInformation.IPAddressInformation
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox("My IP Address is " & IPAdd.Address.ToString)
End Sub
End Class

Dim localIp As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
txtLocal.Text = localIp.AddressList(1).ToString
Notice that I changed the (0) index to (1).

This one works on my side
Dim IPaddressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList
Dim IPaddrPC As String = ""
For Each item In IPaddressList
If item.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
IPaddrPC = item.Address.ToString
Exit For
End If
Next

Related

Solidworks EPDM API IEdmEnumeratorVariable5::SetVar not working as expected

I'm trying to use IEdmEnumeratorVariable5::SetVar to update some file card variables based on user input into a windows form. My code executes, there are no error messages, the file is checked out and checked back in and the appropriate comment is added to the history; however the variables on the card are not updated.
I have verified by stepping through code at runtime that all variables are populated with the correct (as expected) data. The SetVar procedures all go off without a hitch, but the variables on the data card do not change value - even manually refreshing the folder view has no effect.
Below is my code.
This is an add-in application, written as a class-library project in VB using VS Community 2015, with target framework .NET 4.0.
In efforts to make this question more concise; immediately below I've included just the snippet of code doing the set variables work, then I've also included more code so you can get the whole picture if needed.
JUST THE TIP :
This is the code doing the set variables work:
Dim UserManager As IEdmUserMgr5 = .SourceVault
Dim User As IEdmUser5 = UserManager.GetLoggedInUser
CardComment = UserComment & CardComment
CardDate = Today().ToString("yyMMdd", Globalization.CultureInfo.InvariantCulture)
CardBy = User.Name
CardDisposition = UserDisposition
CardVariables.SetVar(DispositionVariable, "#", CardDisposition)
CardVariables.SetVar(CommentVariable, "#", CardComment)
CardVariables.SetVar(ByVariable, "#", CardBy)
CardVariables.SetVar(DateVariable, "#", CardDate)
CardVariables.Flush()
THE BROADER STROKES :
Class module level variables:
Private Structure CommandInfo
Dim SourceVault As IEdmVault11
Dim SourceCommand As EdmCmd
Dim SourceSelection As System.Array
Dim TargetTemplate As System.String
Dim VerifiedPaths As List(Of String)
End Structure
Private ReceivedCommand As CommandInfo
OnCmd procedure (caller):
Public Sub OnCmd(ByRef poCmd As EdmCmd,
ByRef ppoData As System.Array) Implements IEdmAddIn5.OnCmd
Dim CommandToRun As MenuCommand
Try
With ReceivedCommand
.SourceVault = poCmd.mpoVault
.SourceCommand = poCmd
.SourceSelection = ppoData
'Get the command structure for the command ID
Select Case poCmd.meCmdType
Case EdmCmdType.EdmCmd_Menu
CommandToRun = AvailableCommands(.SourceCommand.mlCmdID)
Case EdmCmdType.EdmCmd_CardButton
Select Case True
Case poCmd.mbsComment.ToString.ToUpper.Contains("DISPOSITION")
DispositionRequest()
Case Else : Exit Sub
End Select
Case Else : Exit Sub
End Select
'...... (End Try, End Sub, Etc.)
DispositionRequest procedure (callee):
Private Sub DispositionRequest()
Dim UserDisposition As String
Using Disposition As New DispositionForm
With Disposition
If Not .ShowDialog() = System.Windows.Forms.DialogResult.OK Then Exit Sub
Select Case True
Case .Approve.Checked
UserDisposition = "Approved"
Case .Reject.Checked
UserDisposition = "Rejected"
Case Else : Exit Sub
End Select
End With
End Using
Dim UserComment As String
Using Explanation As New DispositionExplanation
With Explanation
If Not .ShowDialog() = System.Windows.Forms.DialogResult.OK Then Exit Sub
If .ListView1.Items.Count > 0 Then
'do some stuff not relevant to this question...
End If
UserComment = .Comments.Text
End With
End Using
'This next procedure just gets a list of paths from ReceivedCommand.SourceSelection - which is just the ppoData argument from the OnCmd procedure - see code block above!
Dim RequestPaths As List(Of String) = GetSelectedFilePaths()
For Each Path As String In RequestPaths
With ReceivedCommand
Dim RequestFile As IEdmFile5 = .SourceVault.GetFileFromPath(Path)
Dim ParentFolder As IEdmFolder6 = .SourceVault.GetFolderFromPath(System.IO.Path.GetDirectoryName(Path))
Dim UnlockLater As Boolean = False
If Not RequestFile.IsLocked Then
UnlockLater = True
RequestFile.LockFile(ParentFolder.ID, .SourceCommand.mlParentWnd, CInt(EdmLockFlag.EdmLock_Simple))
End If
Dim CardVariables As IEdmEnumeratorVariable5 = RequestFile.GetEnumeratorVariable
'We allow users to re-disposition a request so we want to keep any previous disposition information so it is not lost
Dim CardComment As String = String.Empty
Dim CardBy As String = String.Empty
Dim CardDate As String = String.Empty
Dim CardDisposition As String = String.Empty
Dim Success As Boolean
Const CommentVariable As String = "DispComm"
Const ByVariable As String = "DisposedBy"
Const DateVariable As String = "DisposedDate"
Const DispositionVariable As String = "Disposition"
Success = CardVariables.GetVar(DispositionVariable, "#", CardDisposition)
If Success Then
Success = CardVariables.GetVar(CommentVariable, "#", CardComment)
If Success Then Success = CardVariables.GetVar(ByVariable, "#", CardBy)
If Success Then Success = CardVariables.GetVar(DateVariable, "#", CardDate)
If Success Then CardComment = "Previously dispositioned as: """ & CardDisposition & """ by: " & CardBy & " on: " & CardDate & vbNewLine &
"---------Previous disposition explanation---------" & vbNewLine & CardComment
End If
Dim UserManager As IEdmUserMgr5 = .SourceVault
Dim User As IEdmUser5 = UserManager.GetLoggedInUser
CardComment = UserComment & CardComment
CardDate = Today().ToString("yyMMdd", Globalization.CultureInfo.InvariantCulture)
CardBy = User.Name
CardDisposition = UserDisposition
CardVariables.SetVar(DispositionVariable, "#", CardDisposition)
CardVariables.SetVar(CommentVariable, "#", CardComment)
CardVariables.SetVar(ByVariable, "#", CardBy)
CardVariables.SetVar(DateVariable, "#", CardDate)
CardVariables.Flush()
If UnlockLater Then RequestFile.UnlockFile(lParentWnd:= .SourceCommand.mlParentWnd,
bsComment:="Dispositioned as " & CardDisposition,
lEdmUnlockFlags:=0)
.SourceVault.RefreshFolder(ParentFolder.LocalPath)
End With
Next
End Sub
From the documentation:
bsCfgName : Name of configuration or layout to which to store the variable value; empty string for folders and file types that do not support configurations
I was working with a virtual file, which did not support configurations.
I saw a C example working with a virtual file and they were passing null references, so I reread the documentation and saw that excerpt above, so I changed my code from "#" to String.Empty for the mboconfiguration argument and now it is working!
CardVariables.SetVar(DispositionVariable, String.Empty, CardDisposition)
CardVariables.SetVar(CommentVariable, String.Empty, CardComment)
CardVariables.SetVar(ByVariable, String.Empty, CardBy)
CardVariables.SetVar(DateVariable, String.Empty, CardDate)
CardVariables.Flush()

What Is The Best Way To Run Continous Pings On Multiple IP Addresses

I have an application that currently runs a ping against about 60 different gateways to monitor internet uptime for my clients as I want to know if their internet drops out before they do. So currently my application runs through a loop starting at the first one (runs 4 pings) waits 2 seconds and then moves on to the next gateway address. I have then implemented some code to retry a number of times if the ping results as a failure as I want to be 100% sure that their connection is down before sending an alert.
The problem with this method is that it takes around 1 or 2 minutes (or sometimes longer) before the same gateway is scanned again, meaning that if the connection was to drop out straight after a ping, I wouldn't know for nearly 2 minutes. I know this sounds miniscule but I would much rather instant alerting to my team so they can act on this immediately.
Therefore, my question is: Would it be better (and what would be the impact) of running 60 separate pings (on different threads maybe) instead of cycling through each one. This way I could run a continuous ping on each gateway at the same time. However, I am worried about performance impact on my application and if it will create too much load on the system.
Any advice would be appreciated. Thanks
EDIT
I have created the following code which works but seems to impact a single processor core heavily and whilst this method works without error, it seems to deem the GUI as in-responsive soon after:
Public Sub PingHost()
Try
GatewayScanning = True
For i As Integer = 0 To Gateways.Count - 1
Dim t As New Threading.Thread(AddressOf CheckHostOnline)
t.IsBackground = True
t.Start(Gateways(i))
Next
Catch ex As Exception
ErrorTrap(ex, "OfflineClientHandler: PingHost()")
End Try
End Sub
Public Sub CheckHostOnline(ByVal gw As Object)
Try
Dim _gateway As Gateway_Object = DirectCast(gw, Gateway_Object)
Dim pingSender As New Ping()
Dim options As New PingOptions()
'Dim averageTime As Integer
Dim OfflinePingCount As Integer = 0
' Use the default Ttl value which is 128,
' but change the fragmentation behavior.
options.DontFragment = False
options.Ttl = 128
' Create a buffer of 32 bytes of data to be transmitted.
Dim data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Dim buffer() As Byte = Encoding.ASCII.GetBytes(data)
Dim timeout As Integer = 3000
Do While Not GatewayScanning = False
Dim reply As PingReply = pingSender.Send(_gateway.Gateway, timeout, buffer, options)
If reply.Status = IPStatus.Success Then
Dim resultTime As Integer = GetMs(CInt(reply.RoundtripTime))
_gateway.Status = "ONLINE"
_gateway.Result = resultTime
Else
OfflinePingCount += 1
If OfflinePingCount < (My.Settings.OfflinePingCycleNumber * 4) Then
_gateway.Status = "TIMEOUT"
_gateway.Result = -1
Else
_gateway.Status = "OFFLINE"
_gateway.Result = -1
End If
End If
SyncLock class_OfflineGateways
class_OfflineGateways.UpdateListView(_gateway)
End SyncLock
System.Threading.Thread.Sleep(2000)
Loop
pingSender.Dispose()
Catch ex As Exception
ErrorTrap(ex, "OfflineClientHandler: CheckHostOnline()")
End Try
End Sub
One way to do this is to cycle through the 60 IPs on different threads, and require a five-second (or some amount of time) delay before beginning the cycle again.
Another way is to us asynchronous pings instead of separate threads.
Last time I did this, I ended up using a single thread with 10 ms sleep delay between pings. There were too many ping failures whenever I bunched them together, either with threads or asynch pings. I never did figure out whether the problem was on the server end or on the destination network.
Here's a class I used to ping a list of IP addresses. It (and a bunch of other stuff) ran as a service on an ISP server. (I notice I still have the backgroundworker declared, although it's no longer used.)
Imports System.Net
Imports System.Threading
Imports System.Collections.Generic
Class pingGroup
' used to ping each IP in Targets
Public Targets As New List(Of IPAddress)
Public sectorID As Integer
Public nErrors As Integer = 0
Public Timeout As Integer = pingTimeout
Public PingLog As New List(Of String)
Public PingAvg As Integer = -2 ' -2 = uninit, -1 = error, else average ms excluding the slowest
Public PingTime As DateTime
Public pingCount As Integer = 0
Public pingStarts As Integer = 0
Dim msTotal As Integer = 0
Dim WithEvents bkgPing As System.ComponentModel.BackgroundWorker
Public Sub New(ByVal groupSectorID As Integer)
sectorID = groupSectorID
End Sub
Public Sub Ping()
' run a pingtest once, adding the result incrementally
Dim ip As IPAddress
Dim reply As NetworkInformation.PingReply
Dim ms As Integer
PingTime = Now
If PingLog.Count <= 0 Then PingLog.Add(Format(Now, "G") & " Ping Test")
For Each ip In Targets
Using pPing As New NetworkInformation.Ping
Try
pingStarts = pingStarts + 1
reply = pPing.Send(ip, Timeout)
If reply.Status = NetworkInformation.IPStatus.Success Then
ms = reply.RoundtripTime
pingCount = pingCount + 1
msTotal = msTotal + ms
If pingCount > 0 Then PingAvg = msTotal / pingCount
PingLog.Add(reply.Address.ToString & " " & ms)
Else
nErrors = nErrors + 1
PingLog.Add(Format(Now, "G") & " ---Ping Error: " & ip.ToString & " " & reply.Status.ToString)
End If
Catch ex As Exception
nErrors = nErrors + 1
PingLog.Add(Format(Now, "G") & " ===Ping Error: " & ip.ToString & " " & ex.Message)
End Try
End Using
Thread.Sleep(10)
Next ip
End Sub
End Class

List Network Adapter name with IPv4 address

Im trying to list the only ACTIVE network adapter with its IPv4 addresses on one computer. i have this code but it will list every network card either its connected or not.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
ListView1.Columns.Add("Interface Name", 100)
ListView1.Columns.Add("MAC address", 100)
ListView1.Columns.Add("IPv4 address", 100)
ListView1.Columns.Add("Network Mask", 100)
ListView1.Columns.Add("IPv6 Address", 100)
ListView1.Columns.Add("Link Local Address", 100)
ListView1.Columns.Add("IPv5 Address", 100)
End Sub
Private Sub getinterface()
'get all network interface available in system
Dim nics As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
If nics.Length < 0 Or nics Is Nothing Then
MsgBox("No network interfaces found")
Exit Sub
End If
'if interfaces are found let list them. first clear the listview items
ListView1.Items.Clear()
For Each netadapter As NetworkInterface In nics
'next lets set variable to get interface properties for later use
Dim intproperties As IPInterfaceProperties = netadapter.GetIPProperties()
'now add the network adaptername to the list
ListView1.Items.Add(netadapter.Name)
'now get the mac address of this interface
Dim paddress As PhysicalAddress = netadapter.GetPhysicalAddress()
Dim addbyte As Byte() = paddress.GetAddressBytes()
Dim macaddress As String = ""
'now loop through the bytes value and change it to hex
For i = 0 To addbyte.Length - 1
macaddress &= addbyte(i).ToString("X2") 'change string to hex
'now let separate hex value with -except last one
If i <> addbyte.Length - 1 Then
macaddress &= "-"
End If
Next
'ount item in listview
Dim icount As Integer = ListView1.Items.Count
'use try
Try
With ListView1.Items(icount - 1).SubItems
.Add(macaddress)
'.Add(intproperties.UnicastAddresses(2).Address.ToString)
.Add(intproperties.AnycastAddresses(2).Address.ToString)
.Add(intproperties.UnicastAddresses(2).IPv4Mask.ToString)
.Add(intproperties.UnicastAddresses(0).Address.ToString)
.Add(intproperties.UnicastAddresses(1).Address.ToString)
'.Add( IPAddress.Parse(a).AddressFamily == AddressFamily.InterNetwork )
End With
Catch ex As Exception
End Try
Next
'now lets make auto size columns
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
End Sub
Is there a better way to do this? list the only connected network adapter with IPv4 address. i already try WMI code editor but not sure which one to take for generate adapter name and IP address
Here's the solution I found.
For Each netadapter As NetworkInterface In nics
'next lets set variable to get interface properties for later use
Dim intproperties As IPInterfaceProperties = netadapter.GetIPProperties()
'get first number of IP address.
Dim firstnum As String
Try
firstnum = intproperties.UnicastAddresses(1).Address.ToString()
firstnum = firstnum.Substring(0, firstnum.IndexOf("."))
Catch ex As Exception
'If not IPv4 then
firstnum = "NOPE"
End Try
'check if first number if valid IPv4 address
If Val(firstnum) > 0 And Not Val(firstnum) = 169 And Not Val(firstnum) = 127 Then
'now add the network adaptername to the list
ListView1.Items.Add(netadapter.Name)
Use netadapter.OperationalStatus == OperationalStatus.Up to select the adapters that are active.
(Sorry, that's C#, but the equivalent in VB should be easy.)

Removing certain lines in textbox

I have a proxy list, that is like IP:PORT, and what I need to do is remove all the proxies with port numbers of 8080, 80, 431, and 13. I've tried to use a StreamReader to do this, but to no avail, any help guys? Thank you.
My code efforts:
Using reader As New StreamReader(o.FileName())
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
Dim X As String = line.Contains("8080")
For Each X In NsTextBox1.Text
NsTextBox1.Text = NsTextBox1.Text + X
Exit While
Next
End While
End Using
I recently wrote something that should do the trick nicely, if the proxy list contains 1 IP per line without white space at the end that is.
While not the most optimized code it works pretty well, here's some output of it parsing a list of about 6000 proxies.
You'd use it as such.
IO.File.WriteAllText("C:\ProxyOut.txt", ParseProxyList(IO.File.ReadAllText("C:\ProxyIn.txt"), 8080, 80, 431, 13))
EDIT: oh i just read it was for a textbox, usage should not be that different
TextBoxOut.Text = ParseProxyList(TextBoxIn.Text, 8080, 80, 431, 13))
And the Function itself:
Private Function ParseProxyList(ByVal list As String, ParamArray ports() As Integer)
Dim splitList() As String = list.Split(vbCrLf)
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
Dim outputLinesCount As Integer = 0
For Each line As String In splitList
Dim bContainsPort As Boolean = False
For Each port As Integer In ports
If line.EndsWith(":" & port.ToString) Then
bContainsPort = True
End If
Next
If bContainsPort = False Then
sb.AppendLine(line)
outputLinesCount += 1
End If
Next
MsgBox(splitList.Count.ToString & "->" & outputLinesCount.ToString & " (" & (splitList.Count - outputLinesCount) & " Removed)")
Return sb.ToString
End Function

Netstat with WMI and VBScript

I am working on a project where I need to modify a script used for network documentation. The current script that we use is a modified version of SYDI, found here. What I would like to do is add to this script the ability to execute a netstat -an and have it returned with the rest of the report. I was curious if anyone has used WMI and VBScript to return netstat information and how it might be able to be incorporated into this script.
NOTE: I am not trying to promote a product and I am not affiliated with the SYDI project.
You could run netstat and capture the result like the script here under, but much info is also available from activeX but the i would need to know what information you need exactly.
set sh = CreateObject("Wscript.Shell")
set Connections = CreateObject("Scripting.Dictionary")
call Main()
Function Main()
call GetConnections()
call ProcessConnections()
End Function
Function GetConnections()
i = 0
set shExec = sh.Exec("netstat -f")
Do While Not shExec.StdOut.AtEndOfStream
Line = shExec.StdOut.ReadLine()
If Instr(Line, "TCP") <> 0 Then
Set Connection = New NetworkConnection
Connection.ParseText(Line)
call Connections.Add(i, Connection)
i = i + 1
End If
Loop
End Function
Function ProcessConnections()
For Each ConnectionID in Connections.Keys
wscript.echo ConnectionID & Connections(ConnectionID).RemoteIP
Next
End Function
Class NetworkConnection
Public Protocol
Public LocalIP
Public LocalPort
Public RemoteIP
Public RemotePort
Public Sub ParseText(Line)
dim i
For i = 5 to 2 Step -1
Line = Replace(Line, String(i, " "), " ")
Next
Line = Replace(Line, ":", " ")
Line = Right(Line, Len(Line) - 1)
Line = Split(Line, " ")
Protocol = Line(0)
LocalIP = Line(1)
LocalPort = Line(2)
RemoteIP = Line(3)
RemotePort = Line(4)
End Sub
Private Sub Class_Initialize
'MsgBox "Initialized NetworkConnection object"
End Sub
End Class
EDIT: based on the comment of OP here a simplified version
set sh = CreateObject("Wscript.Shell")
call GetConnections()
Function GetConnections()
i = 0
set shExec = sh.Exec("netstat -an")
Do While Not shExec.StdOut.AtEndOfStream
Wscript.Echo shExec.StdOut.ReadLine()
Loop
End Function