Problem getting IP address vb 2008

korae

Member
Joined
Jan 24, 2010
Messages
22
Programming Experience
Beginner
I have this code that gets the local IP, It works when I'm directly connected to my ISP modem but when I'm in a router it displays the mac instead of the IP. I don't know what's missing in the code.

Imports System.Net

Private Sub GetIPAddress()

Dim ip As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName)

Label25.Text = ip.AddressList.GetValue(0).ToString
End Sub
 
It is not a MAC address, it is the IPv6 address (the new thing). If you want the mapped IPv4 address you can loop the list and check for InterNetwork type address familiy:
VB.NET:
For Each adr As Net.IPAddress In ip.AddressList
    If adr.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
        s = adr.ToString
        Exit For
    End If
Next
Notice that when you're connected to a router it is the local private network ip that is returned, not the "local" public ip that router has towards the internet.
 
I hope this help

VB.NET:
Dim oAddr As System.Net.IPAddress
Dim sAddr As String
With System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
oAddr = New System.Net.IPAddress(.AddressList(0).Address)
sAddr = oAddr.ToString
End With
Label.Text = sAddr
 
AddressList(0) is same as AddressList.GetValue(0), you can't rely on the first address being InterNetwork.
 
It is not a MAC address, it is the IPv6 address (the new thing). If you want the mapped IPv4 address you can loop the list and check for InterNetwork type address familiy:
VB.NET:
For Each adr As Net.IPAddress In ip.AddressList
    If adr.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
        s = adr.ToString
        Exit For
    End If
Next
Notice that when you're connected to a router it is the local private network ip that is returned, not the "local" public ip that router has towards the internet.

Thank you for the help John! Its now working! Thank you very much!
 
Back
Top