You can use LINQ to filter the results:
Dim ipHostEntry = Dns.GetHostEntry(Dns.GetHostName)
Dim ipAddress = ipHostEntry.AddressList.FirstOrDefault(Function(ip) ip.AddressFamily = AddressFamily.InterNetwork)
If ipAdress IsNot Nothing Then
' Output ipAdress.ToString()
Else
' No IPv4 address could be retrieved
End If
Explanation:
IPHostAddress.AddressList
returns an Array(Of IPAddress)
which implements the IEnumerable
interface and can therefore be enumerated by LINQ expressions.
FirstOrDefault
will return the first element from the AddressList array that matched the predicate lambda function that is submitted as first and only parameter of FirstOrDefault
. The predicate function has to be written to return a boolean.
The array is iterated from the first to the last element, and for each element the lambda function is evaluated, where its parameter ip
is the current iteration item. With ip.AddressFamily = AddressFamily.InterNetwork
we determine whether the current item is an IPv4 address. If so, the expression evaluates true
and the item is returned by FirstOrDefault
. If it evaluates to false
, the next item from the array is checked and so on. If no element matches the predicate, FirstOrDefault
returns the default value, in this case Nothing
(N. B.: the extension First
works the same way but throws an exception if no item matches the predicate; both First
and FirstOrDefault
can be called without any arguments, they return the first element of the sequence then).
I prefer the extension methods based notation as above, but you can use the original From In Where Select
LINQ notation as well if you prefer:
Dim ipAddress = (From ip In ipHostEntry.AddressList
Where ip.AddressFamily = AddressFamily.InterNetwork
Select ip)(0)
Note that (0)
is the argument for another extension method ElementAtOrDefault(index As Integer)
in this case.