Search code examples
vb.netipv4

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?


Solution

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