Finding IP from vb.net

  • Thread starter Thread starter HardySpicer
  • Start date Start date
H

HardySpicer

The code below seems to work but it gives me the IPv6 IP address in ip
(0) (the array of IPs). How can I get the IP4? In fact I am not too
worried since I am really after the Geo location from the IP as
part2! So any type of IP will do as long as I can get the location
from it.

Hardy


Imports System.Collections.Specialized
Imports System.Net

Public Class Form1
Private Function GetIPs() As StringCollection
Dim localIP = New StringCollection()
Dim localHostName = Dns.GetHostName()
Dim hostEntry = Dns.GetHostEntry(localHostName)
' Grab all ip addesses.
For Each ipAddr As IPAddress In hostEntry.AddressList
localIP.Add(ipAddr.ToString())
Next
GetIPs = localIP
End Function

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim ip As StringCollection
ip = GetIPs()
' Output the IP address to a Label
Label1.Text = ip(0)
End Sub

Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Label1.Click

End Sub
End Class
 
HardySpicer said:
The code below seems to work but it gives me the IPv6 IP address in ip
(0) (the array of IPs). How can I get the IP4? In fact I am not too
worried since I am really after the Geo location from the IP as
part2! So any type of IP will do as long as I can get the location
from it.

Hardy


Imports System.Collections.Specialized
Imports System.Net

Public Class Form1
Private Function GetIPs() As StringCollection
Dim localIP = New StringCollection()
Dim localHostName = Dns.GetHostName()
Dim hostEntry = Dns.GetHostEntry(localHostName)
' Grab all ip addesses.
For Each ipAddr As IPAddress In hostEntry.AddressList
localIP.Add(ipAddr.ToString())
Next
GetIPs = localIP
End Function

I wouldn't recommend the way using the host name because the DNS
isn't required to get IP information in this case. I'd enumerate
them this way:

Dim NInterfaces As NetworkInterface()

NInterfaces = NetworkInterface.GetAllNetworkInterfaces

For Each NInterface As NetworkInterface In NInterfaces
Debug.Print("Interface: " & NInterface.Description)

For Each Info As IPAddressInformation _
In NInterface.GetIPProperties().UnicastAddresses

Debug.Print(" " & Info.Address.ToString())
Next
Next

Then you can check whether Info.Address.AddressFamily = InternetworkV6
 
Back
Top