How can get local IP Address?

Asked by At

This is my code get IP Address:

    Dim ip
    Dim strHostName = System.Net.Dns.GetHostName()   
    Dim iphe As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)
    For Each ipheal As System.Net.IPAddress In iphe.AddressList
        If ipheal.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork Then
            ip = ipheal
            Exit For
        End If

If My PC connecting to a Network by VPN. It return ip of Network VPN.

I only want get local ip except Network VPN.

1 Answers

Community On

You can list all IP addresses in the list and based on that list make decision. So, instead of exiting in FOR loop, process all IP addresses. That is the best you can do. See the snippet below.

Imports System.Net.Sockets

Module Module1

    Sub Main()

        Dim iphe As Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
        Dim ip = iphe.AddressList.Where(Function(n) n.AddressFamily = AddressFamily.InterNetwork)
        For Each i  In ip

    End Sub

End Module