List Network Adapter name with IPv4 address - vb.net

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.)

Related

Speeding up "Old" string parsing methodes using PLINQ or Async/Await or TPL, etc

As (hopefully) all developers, I've developed over the years and am now at the point that OOP and functional programming is a daily costs. Recently I've bumped into and "old" (2 years) DLL of my that reads in a TCP stream, drops the incoming string (which end with a line feed) into a ConcurrentQueue(Of String). Then a second Backgroundworker loops over the ConcurrentQueue(Of String) and dequeue's the string and parses it.
Depending on the request command i send to the TCP server i gat get one line or several hunders of line. Also when nothing is asked the TCP server send's nothing. It is completely event driven.
With the new and efficient Technics of PLINQ, Async/Await and TPL i am determine to make this faster/more efficient. Currently i'm brainstorming on how to do this and am asking you to think with me or give some good advice.
So let's dig deeper into what i have now:
It al starts with two Backgroundworkers, One for Reading and One for Parsing.
The Reading Backgroundworker:
This backgroundworker job is to read the incomming data and make sure to keep reading until a Linefeed is passed. Then it cuts into a string and drops it into a ConcurrentQueue(Of String). The code looks like this:
Private Sub bgwReceive_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgwTCP_Receive.DoWork
Dim strRXData As String = String.Empty
Dim intLfpos As Integer = 0
Try
Do Until bgwTCP_Receive.CancellationPending
'while the client is connected, continue to wait for and read data
While _Client.Connected AndAlso _ClientStream.CanRead
Dim buffer(_Client.ReceiveBufferSize - 1) As Byte
Dim read As Integer = _ClientStream.Read(buffer, 0, buffer.Length)
'Put the new data in the queue
If read > 0 Then
'Add incomming data to the buffer string
strRXData &= Text.Encoding.ASCII.GetString(buffer, 0, read)
'Replace "0 padding"
strRXData.Replace(Chr(0), String.Empty)
'Now check if we have a Linefeed in our buffer string
While strRXData <> String.Empty
'Get the position of the first linefeed
intLfpos = strRXData.IndexOf(vbLf)
'Now check if we find something.
If intLfpos < 0 Then Exit While
'There is a line feed, it is time to add it to the incomming data queue
IncommingData.Enqueue(strRXData.Substring(0, intLfpos - 1))
'Now remove the command from the buffer string
strRXData = strRXData.Substring(intLfpos + 1, strRXData.Length - intLfpos - 1)
End While
End If
'Check if we have to stop
If bgwTCP_Receive.CancellationPending Then e.Cancel = True : Exit Do
Threading.Thread.Sleep(1)
End While
Threading.Thread.Sleep(100)
Loop
e.Cancel = True
Catch op As OperationCanceledException
Throw New Exception("TCP Reading cancelled")
Catch se As SocketException
Throw New Exception("Socket unknown error. Native error code: " & se.NativeErrorCode)
Catch IOex As IOException
Throw New Exception("Socket timeout while receiving data from [" & TCP_ServerIP.ToString & "]")
End Try
End Sub
The Parsing Backgroundworker: This backgroundworker job is to parse the strings in the ConcurrentQueue(Of String). In this backgroundworker there is a big Select case that looks at the first word in the string. This determines what to do.
The received protocol is very simple but unfortunately it hasn't a sollid structure like JSON. A string would look like this: IND PARM1:"Hello world!" PARM2:1.4.8 \CrLf
As you can see it is very simple and plain. The IND indicate the Command, like VER is for VERSION string. IND is always 3 chars long. Then comes the parameters. The parameter name is always 4 chars long. If it is between double quotes it is a string, else its something like a double/integer/IP address (X.X.X.X). Keep in mind that original it is a string. In my parser i parse it to the object properties. The code looks like this:
Private Sub bgwProcessQueue_DoWork(sender As Object, e As DoWorkEventArgs) Handles bgwProcessQueue.DoWork
Dim strNewLine As String = String.Empty
Dim strSubLine As String = String.Empty
Try
'Loop until program has stopped
Do Until bgwProcessQueue.CancellationPending
'Only process when something is in the queue
If TCP_Connection.IncommingData.TryDequeue(strNewLine) Then
'If Backgroundworker has to cancel than cancel
If bgwProcessQueue.CancellationPending Then Exit Do
Select Case True
Case strNewLine.StartsWith("VER") 'Example: VER PRM1:1.1 PRM2:"Hi there" PRM3:1.1.1 PRM4:8/0 PRM5:8
'First check if all the needed values are there, if not resend the command
If strNewLine.Contains("PRM1:") AndAlso strNewLine.Contains("PRM2:") AndAlso strNewLine.Contains("PRM3:") AndAlso strNewLine.Contains("PRM4:") AndAlso strNewLine.Contains("PRM5:") Then
'Get versions and devicename
Me.Param1 = GetSubstring(strNewLine, "PRM1:", " ")
Me.Param2 = GetSubstring(strNewLine, "PRM2:", " ")
Me.Param3 = GetSubstring(strNewLine, "PRM3:", " ")
Me.Param4 = GetSubstring(strNewLine, "PRM4:", " ")
Me.Param5 = GetSubstring(strNewLine, "PRM5:", " ")
Else
'Commando was invalid, resend the command
Log.Message(LogLevel.Warning, "VER Messages was incompleet, resending VER command")
SendData("VER")
End If
Case strNewLine.StartsWith("ERROR")
Log.Message(LogLevel.Warning, strNewLine)
End Select
End If
'Clear any old data
strNewLine = String.Empty
'Sleep
Threading.Thread.Sleep(1)
Loop
e.Cancel = True
Catch ex As Exception
Log.Exception(ex)
End Try
End Sub
Private Function GetSubstring(text As String, StartValue As String, EndValue As String) As String
Try
'If we can't find the Start value we can't do anything
If Not text.Contains(StartValue) Then Return String.Empty
'Find the index of the Start and End value
intStartValueIndex = text.IndexOf(StartValue) + StartValue.Length
intEndValueIndex = text.IndexOf(EndValue, intStartValueIndex)
'If no Endvalue index was found then get the end of the string
If intEndValueIndex < intStartValueIndex Then intEndValueIndex = text.Length
'Return the substring en remove quetes
Return text.Substring(intStartValueIndex, intEndValueIndex - intStartValueIndex).Replace("""", "")
Catch ex As Exception
Log.Exception(ex)
Return String.Empty
End Try
End Function
Hopefully all above is understandable. I was thinking of looping through the ConcurrentQueue(Of String) with a Parrallel.ForEach Wich passes the Dequeued string into a sub that does the parsing. At the reading side, my inspiration is empty at the moment...

Change label text in foreach loop

i want to update a label while a foreach-loop.
The problem is: the program waits until the loop is done and then updates the label.
Is it possible to update the label during the foreach-loop?
Code:
Dim count as Integer = 0
For Each sFile as String in Files
'ftp-code here, works well
count = count+1
progressbar1.value = count
label1.text = "File " & count & " of 10 uploaded."
next
Thanks in advance
Label is not updated because UI thread is blocked while executing your foreach loop.
You can use async-await approach
Private Async Sub Button_Click(sender As Object, e As EventArgs)
Dim count as Integer = 0
For Each sFile as String in Files
'ftp-code here, works well
count = count+1
progressbar1.value = count
label1.text = "File " & count & " of 10 uploaded."
Await Task.Delay(100)
Next
End Sub
Because you will work with Ftp connections, which is perfect candidate for using async-await.
The Await line will release UI thread which will update label with new value, and continue from that line after 100 milliseconds.
If you will use asynchronous code for ftp connection , then you don't need Task.Delay
You've already accepted an answer but just as an alternative a BackgroundWorker can also be used for something like this. In my case the FTP to get the original files happens very quickly so this snippet from the DoWork event is for downloading those files to a printer.
Dim cnt As Integer = docs.Count
Dim i As Integer = 1
For Each d As String In docs
bgwTest.ReportProgress(BGW_State.S2_UpdStat, "Downloading file " & i.ToString & " of " & cnt.ToString)
Dim fs As New IO.FileStream(My.Application.Info.DirectoryPath & "\labels\" & d, IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
Dim bytes() As Byte = br.ReadBytes(CInt(br.BaseStream.Length))
br.Close()
fs.Close()
For x = 0 To numPorts - 1
If Port(x).IsOpen = True Then
Port(x).Write(bytes, 0, bytes.Length)
End If
Next
If bytes.Length > 2400 Then
'these sleeps are because it is only 1-way comm to printer so I have no idea when printer is ready for next file
System.Threading.Thread.Sleep(20000)
Else
System.Threading.Thread.Sleep(5000)
End If
i = i + 1
Next
In the ReportProgress event... (of course, you need to set WorkerReportsProgress property to True)
Private Sub bgwTest_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwTest.ProgressChanged
Select Case e.ProgressPercentage
'BGW_State is just a simple enum for the state,
'which determines which UI controls I need to use.
'Clearly I copy/pasted from a program that had 15 "states" :)
Case BGW_State.S2_UpdStat
Dim s As String = CType(e.UserState, String)
lblStatus.Text = s
lblStatus.Refresh()
Case BGW_State.S15_ShowMessage
Dim s As String = CType(e.UserState, String)
MessageBox.Show(s)
End Select
End Sub
Is it not enough to use Application.DoEvents()? This clears the build up and you should be able to see the text fields being updated very quickly.

Opening and closing multiple forms from a main form in VB.net

In my project (kind of a screen saver) I have a main form and second form (PicView).
I want to open many instances of the second form and display a picture in it.
I can do that fine, but when I have opened e.g. 4 forms I would like to close the first before opening the next one so that the total number of forms stays at 4.
The problem I have is that the closing routine does not know about the form instances and the debugger tells me to create a new instance, but I would like to use the existing ones.
How can I make the form names visible to the main routine or do I need to pass reference to the created forms?
Thanks
Private Sub btnTest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
gsPic1 = "D:\My Stuff\411CANON\IMG_1161.JPG"
gsPic2 = "D:\My Stuff\411CANON\IMG_1167.JPG"
gsPic3 = "D:\My Stuff\411CANON\IMG_1174.JPG"
gsPic4 = "D:\My Stuff\411CANON\IMG_1178.JPG"
ScreenSavePicIndex(gsPic1, 1)
Application.DoEvents()
ScreenSavePicIndex(gsPic2, 2)
Application.DoEvents()
ScreenSavePicIndex(gsPic3, 3)
Application.DoEvents()
ScreenSavePicIndex(gsPic4, 4)
MsgBox("Now Closing 1")
CloseScreenSaverPic(1)
Application.DoEvents()
MsgBox("Now Closing 3")
CloseScreenSaverPic(3)
Application.DoEvents()
MsgBox("Now Closing 4")
CloseScreenSaverPic(4)
Application.DoEvents()
End Sub
Private Sub CloseScreenSaverPic(ByVal iIndex As Integer)
Dim frmPicViewerScrSav(iIndex) As PicView
frmPicViewerScrSav(iIndex) = New PicView
frmPicViewerScrSav(iIndex).Close()
End Sub
Private Sub ScreenSavePicIndex(ByVal sFilePathandName As String, iIndex As Integer)
Dim iTargetHeight As Integer
Dim iTargetWidth As Integer
Dim dFactorHeight As Double
Dim dFactorWidth As Double
Dim objImage As System.Drawing.Image
Try
objImage = System.Drawing.Image.FromFile(sFilePathandName)
Catch ex As Exception
objImage = Nothing
End Try
Dim frmPicViewerScrSav(iIndex) As PicView
frmPicViewerScrSav(iIndex) = New PicView
Dim dFactor As Double
dFactor = 1
frmPicViewerScrSav(iIndex).FormBorderStyle = Windows.Forms.FormBorderStyle.None
iTargetWidth = Screen.PrimaryScreen.Bounds.Width / giScreenSavePicSize
iTargetHeight = Screen.PrimaryScreen.Bounds.Height / giScreenSavePicSize
'Check if the pic is bigger than what we want to display
If objImage.Width > iTargetWidth Then
'if it is wider then we need to find out how much bigger it is by factor
dFactorWidth = iTargetWidth / objImage.Width
End If
If objImage.Height > iTargetHeight Then
'if it is higher then we need to find out how much bigger it is by factor
dFactorHeight = iTargetHeight / objImage.Height
End If
If dFactorWidth > dFactorHeight Then
dFactor = dFactorWidth
Else
dFactor = dFactorHeight
End If
'Console.WriteLine("Factor is: " & dFactor)
frmPicViewerScrSav(iIndex).Width = objImage.Width * dFactor
frmPicViewerScrSav(iIndex).Height = objImage.Height * dFactor
objImage.Dispose()
Dim r As New Random()
Dim x As Integer = r.Next(Screen.PrimaryScreen.Bounds.Width - frmPicViewerScrSav(iIndex).Width)
Dim y As Integer = r.Next(Screen.PrimaryScreen.Bounds.Height - frmPicViewerScrSav(iIndex).Height)
Dim p As New Point(x, y)
'Console.WriteLine("Putting it at x= " & x & ", y= " & y)
frmPicViewerScrSav(iIndex).Location = p
frmPicViewerScrSav(iIndex).PictureBox1.Hide()
frmPicViewerScrSav(iIndex).PictureBox1.ImageLocation = sFilePathandName
frmPicViewerScrSav(iIndex).PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
frmPicViewerScrSav(iIndex).PictureBox1.Show()
frmPicViewerScrSav(iIndex).Show()
End Sub

Binary Search or Insertion Sort with list view [Visual Basic .net]

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language
Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub

get local IPv4 of computer using 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