Wednesday, October 19, 2011

Get Domain, PC Name and IP Address of your local network using VB.Net

Import below namespace in your project:


Imports System.DirectoryServices

Imports System.Net 


Use this functions to get data and store in to Data table :


Private Sub GetIPS()
        Dim child As DirectoryEntry
        Dim Parent As New DirectoryEntry()
        Try
            Parent.Path = "WinNT:"
            For Each child In Parent.Children

                Select Case child.SchemaClassName

                    Case "Domain"

                        Dim ParentDomain As New TreeNode(child.Name)
                        Dim SubChild As DirectoryEntry
                        Dim SubParent As New DirectoryEntry()
                        SubParent.Path = "WinNT://" & child.Name

                        For Each SubChild In SubParent.Children

                            Select Case SubChild.SchemaClassName
                                Case "Computer"
                                    Dim ipadd As String = GetIPAddress(SubChild.Name)
                                    CreateDT(child.Name, SubChild.Name, ipadd)
                            End Select
                        Next
                End Select

            Next

        Catch Excep As Exception
            MsgBox("Error While Reading Directories")
        Finally
            Parent = Nothing
        End Try
    End Sub



    Private Sub CreateDT(ByVal Domain As String, ByVal PCName As String, ByVal IpAddress As String)
        If dt.Rows.Count = 0 Then
            dt.Columns.Add("domain")
            dt.Columns.Add("pcname")
            dt.Columns.Add("ipaddress")
        End If

        Dim dr As DataRow
        dr = dt.NewRow()
        dr("domain") = Domain
        dr("pcname") = PCName
        dr("ipaddress") = IpAddress
        dt.Rows.Add(dr)
    End Sub

  Function GetIPAddress(ByVal CompName As String) As String
        Dim oAddr As System.Net.IPAddress
        Dim sAddr As String
        Try
            With System.Net.Dns.GetHostByName(CompName)
                oAddr = New System.Net.IPAddress(.AddressList(0).Address)
                sAddr = oAddr.ToString
            End With

            GetIPAddress = sAddr
        Catch Excep As Exception
            MsgBox(Excep.Message, MsgBoxStyle.OkOnly, "GET IP ADDRESS")
        Finally

        End Try
    End Function 
Sample Code Download Link : http://www.adrive.com/public/406bd58f991bf0afb884cadc2b78da6a28417082c16938c0bedd505ac224afbd.html

No comments:

Post a Comment