[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Find out LAN IP address in VB .Net 2008

Posted on 2009-07-08
5
Medium Priority
?
1,989 Views
Last Modified: 2012-05-07
How do I find out my computer's LAN IP address in VB 2008?
0
Comment
Question by:freebullets
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
5 Comments
 
LVL 15

Expert Comment

by:JackOfPH
ID: 24809649
Try this class

:)
'---------------------------------------------------------------------
'  This file is part of the Microsoft .NET Framework SDK Code Samples.
' 
'  Copyright (C) Microsoft Corporation.  All rights reserved.
' 
'This source code is intended only as a supplement to Microsoft
'Development Tools and/or on-line documentation.  See these other
'materials for detailed information regarding Microsoft code samples.
' 
'THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
'KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
'IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
'PARTICULAR PURPOSE.
'---------------------------------------------------------------------
 
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Globalization
 
 
Public Class NetworkInformation
 
    Dim networkInterfaces() As NetworkInterface
    Dim currentInterface As NetworkInterface
 
    Delegate Sub NetworkAddressChangedCallback()
    Delegate Sub NetworkAvailabilityCallback( _
        ByVal isNetworkAvailable As Boolean)
 
    Private Sub NetworkInformation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Wire up the NetworkAddressChanged events so we can get notified
        ' when an address change occurs on	any	of the network interfaces.
        ' These changes occur when the interface changes operational
        ' status (up/down) or a new interface is added. 
        AddHandler System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged, AddressOf Me.networkChange_NetworkAvailabilityChanged
        AddHandler System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged, AddressOf Me.networkChange_NetworkAddressChanged
 
        ' Populate the	global interfaces container with the list of all
        ' network interfaces.
        networkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces
 
        ' Determine if	the	network	is available at	startup.
        UpdateNetworkAvailability(System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
 
        ' Update the information for the network intefaces.
        UpdateNetworkInformation()
    End Sub
 
    Private Sub networkChange_NetworkAvailabilityChanged( _
        ByVal sender As Object, ByVal e As NetworkAvailabilityEventArgs)
        Me.Invoke( _
            New NetworkAvailabilityCallback( _
                AddressOf UpdateNetworkAvailability), _
            New Object() {e.IsAvailable})
    End Sub
 
    Private Sub networkChange_NetworkAddressChanged( _
        ByVal sender As Object, ByVal e As EventArgs)
        Me.Invoke( _
            New NetworkAddressChangedCallback( _
                AddressOf UpdateNetworkInformation))
    End Sub
 
    Private Sub UpdateNetworkInformation()
        networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
        networkInterfacesComboBox.Items.Clear()
 
        For Each nic As NetworkInterface In networkInterfaces
            networkInterfacesComboBox.Items.Add(nic.Description)
        Next
 
        If networkInterfaces.Length = 0 Then
            networkInterfacesComboBox.Items.Add( _
                "No NICs found on the machine.")
        Else
            currentInterface = networkInterfaces(0)
            UpdateCurrentNicInformation()
        End If
 
        networkInterfacesComboBox.SelectedIndex = 0
    End Sub
 
    Private Sub UpdateCurrentNicInformation()
        ' Set the DNS suffix if any exists
        Dim ipProperties As IPInterfaceProperties = _
            currentInterface.GetIPProperties()
        dnsSuffixTextLabel.Text = ipProperties.DnsSuffix.ToString()
 
        ' Display the IP address information associated with this
        ' interface including anycast,	unicast, multicast,	DNS	servers,
        ' WINS	servers, DHCP servers, and the gateway
        addressListView.Items.Clear()
 
        Dim anycastInfo As IPAddressInformationCollection = _
            ipProperties.AnycastAddresses
        For Each info As IPAddressInformation In anycastInfo
            InsertAddress(info.Address, "Anycast")
        Next
        Dim unicastInfo As UnicastIPAddressInformationCollection = _
            ipProperties.UnicastAddresses
        For Each info As UnicastIPAddressInformation In unicastInfo
            InsertAddress(info.Address, "Unicast")
        Next
        Dim multicastInfo As MulticastIPAddressInformationCollection = _
            ipProperties.MulticastAddresses
        For Each info As MulticastIPAddressInformation In multicastInfo
            InsertAddress(info.Address, "Multicast")
        Next
        Dim gatewayInfo As GatewayIPAddressInformationCollection = _
            ipProperties.GatewayAddresses
        For Each info As GatewayIPAddressInformation In gatewayInfo
            InsertAddress(info.Address, "Gateway")
        Next
 
        Dim ipAddresses As IPAddressCollection = _
            ipProperties.WinsServersAddresses
        InsertAddresses(ipAddresses, "WINS Server")
        ipAddresses = ipProperties.DhcpServerAddresses
        InsertAddresses(ipAddresses, "DHCP Server")
        ipAddresses = ipProperties.DnsAddresses
        InsertAddresses(ipAddresses, "DNS Server")
 
    End Sub
 
    Private Sub InsertAddresses( _
        ByVal ipAddresses As IPAddressCollection, _
        ByVal addressType As String)
        For Each address As IPAddress In ipAddresses
            InsertAddress(address, addressType)
        Next
    End Sub
 
    Private Sub InsertAddress( _
        ByVal address As IPAddress, _
        ByVal addressType As String)
        Dim listViewInformation(2) As String
        listViewInformation(0) = address.ToString()
        listViewInformation(1) = addressType
 
        Dim item As ListViewItem = New ListViewItem(listViewInformation)
        addressListView.Items.Add(item)
    End Sub
 
    Private Sub UpdateNetworkAvailability( _
        ByVal isNetworkAvailable As Boolean)
        If isNetworkAvailable Then
            networkAvailabilityTextLabel.Text = _
                "At least one network interface is up."
        Else
            networkAvailabilityTextLabel.Text = _
                "The network is not currently available."
        End If
    End Sub
 
    Private Sub networkInterfacesComboBox_SelectedIndexChanged( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles networkInterfacesComboBox.SelectedIndexChanged
        currentInterface = _
            networkInterfaces(networkInterfacesComboBox.SelectedIndex)
        UpdateCurrentNicInformation()
    End Sub
 
    Private Sub updateInfoTimer_Tick( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles updateInfoTimer.Tick
        UpdateNicStats()
    End Sub
 
    Private Sub UpdateNicStats()
        ' Get the IPv4	statistics for the currently selected interface
        Dim ipStats As IPv4InterfaceStatistics = _
            currentInterface.GetIPv4Statistics()
 
        Dim numberFormat As NumberFormatInfo = _
            NumberFormatInfo.CurrentInfo
        Dim bytesReceivedInKB As Long = ipStats.BytesReceived / 1024
        Dim bytesSentInKB As Long = ipStats.BytesSent / 1024
 
        speedTextLabel.Text = GetSpeedString(currentInterface.Speed)
        bytesReceivedTextLabel.Text = _
            bytesReceivedInKB.ToString("N0", numberFormat) + " KB"
        bytesSentTextLabel.Text = _
            bytesSentInKB.ToString("N0", numberFormat) + " KB"
 
        operationalStatusTextLabel.Text = _
            currentInterface.OperationalStatus.ToString()
        supportsMulticastTextLabel.Text = _
            currentInterface.SupportsMulticast.ToString()
    End Sub
 
    Private Shared Function GetSpeedString(ByVal speed As Long) As String
        Select Case speed
            Case 10000000
                GetSpeedString = "10 MB"
            Case 11000000
                GetSpeedString = "11 MB"
            Case 54000000
                GetSpeedString = "54 MB"
            Case 100000000
                GetSpeedString = "100 MB"
            Case 1000000000
                GetSpeedString = "1 GB"
            Case Else
                GetSpeedString = speed.ToString(NumberFormatInfo.CurrentInfo)
        End Select
 
 
    End Function
 
End Class

Open in new window

0
 
LVL 53

Expert Comment

by:Dhaest
ID: 24811102
Easier solution:

Dim localIP() As System.Net.IPAddress = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName)
Dim strLocalIP As String = localIP(0).ToString

Open in new window

0
 
LVL 1

Author Comment

by:freebullets
ID: 24814533
Dim localIP() As System.Net.IPAddress = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName)

localIP(0).ToString = "fe80::3419:ac20:7e2c:217b%9"
localIP(1).ToString = "fe80::5efe:192.168.0.101%15"
localIP(2).ToString = "fe80::245e:1861:9ea6:5152%10"
localIP(3).ToString = "192.168.0.101"
localIP(4).ToString = "2001:0:4137:9e50:245e:1861:9ea6:5152"

I need ONE IP address which is the local IPv4 address used to connect to the internet.  I made this function which seems to work, but if there's any simpler ways, I'm open to suggestions.
  Function GetLocalIP() As System.Net.IPAddress
    Dim localIP() As System.Net.IPAddress = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName)
    For Each current As System.Net.IPAddress In localIP
      If current.ToString Like "*[.]*[.]*[.]*" Then
        Try
          Dim SplitVar() As String = current.ToString.Split(".")
          If Len(SplitVar(0)) <= 3 And Len(SplitVar(1)) <= 3 And Len(SplitVar(2)) <= 3 And Len(SplitVar(3)) <= 3 Then
            Return current
          End If
        Catch ex As Exception
        End Try
      End If
    Next
  End Function

Open in new window

0
 
LVL 53

Accepted Solution

by:
Dhaest earned 200 total points
ID: 24923123
Like all the experts already sugggested, that's seems the way to retrieve the ip-address. The GetHostAddresses returns always multiple formats, so you need to filter the right one like you did
0
 
LVL 1

Author Closing Comment

by:freebullets
ID: 31601383
It'd have been nice if you could of posted a function like that, but thanks anyways for getting me on the right track.
0

Featured Post

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
You can of course define an array to hold data that is of a particular type like an array of Strings to hold customer names or an array of Doubles to hold customer sales, but what do you do if you want to coordinate that data? This article describes…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question