Detect PCs On Network

Posted on 2006-04-07
Medium Priority
Last Modified: 2008-02-26

Is it possible to detect the number of PCs on your network?


Detect the PC Names on the network?

Question by:narmi2
  • 4
  • 3
  • 2
  • +2
LVL 30

Expert Comment

by:Irwin Santos
ID: 16402054
START-RUN.. type in CMD <enter> in the DOS window type


it will list all your connected workstations.
LVL 48

Accepted Solution

Mikal613 earned 800 total points
ID: 16402290
LVL 41

Assisted Solution

graye earned 800 total points
ID: 16402294
Here is chunk of code that demonstrates 3 different ways to get a listing of PCs on the LAN (by using th "My Network Places", by "NT-style Domain", or by "Active Directory-style Domain".

Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.DirectoryServices
Imports System.Collections.Specialized
Module GetNetList

    'NET_API_STATUS NetServerEnum(
    '  LPCWSTR servername,
    '  DWORD level,
    '  LPBYTE* bufptr,
    '  DWORD prefmaxlen,
    '  LPDWORD entriesread,
    '  LPDWORD totalentries,
    '  DWORD servertype,
    '  LPCWSTR domain,
    '  LPDWORD resume_handle
    Private Declare Unicode Function NetServerEnum Lib "Netapi32.dll" ( _
        ByVal servername As Integer, _
        ByVal level As Integer, _
        ByRef bufptr As IntPtr, _
        ByVal prefmaxlen As Integer, _
        ByRef entriesread As Integer, _
        ByRef totalentries As Integer, _
        ByVal servertype As Integer, _
        ByVal domain As String, _
        ByRef resume_handle As Integer) As Integer

    'NET_API_STATUS NetApiBufferFree(
    '  LPVOID Buffer
    Private Declare Function NetApiBufferFree Lib "Netapi32.dll" ( _
        ByVal Buffer As IntPtr) As Integer

    Private Const SV_TYPE_ALL As Long = &HFFFFFFFF

    'typedef struct _SERVER_INFO_101 {
    '  DWORD sv101_platform_id;
    '  LPWSTR sv101_name;
    '  DWORD sv101_version_major;
    '  DWORD sv101_version_minor;
    '  DWORD sv101_type;
    '  LPWSTR sv101_comment;
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode, Pack:=4)> _
    Private Structure SERVER_INFO_101
        Dim sv101_platform_id As Integer
        Dim sv101_name As String
        Dim sv101_version_major As Integer
        Dim sv101_version_minor As Integer
        Dim sv101_type As Integer
        Dim sv101_comment As String
    End Structure

    Function GetPCNetList(ByVal DomainName As String, Optional ByVal filter As String = "") As String()
        Dim ServerInfo As New SERVER_INFO_101
        Dim i, MaxLenPref, level, ret, EntriesRead, TotalEntries, ResumeHandle As Integer
        Dim BufPtr, iPtr As IntPtr
        Dim ans(-1) As String
        Dim num As Integer

        ' let's do it!
        MaxLenPref = -1
        level = 101
        ret = NetServerEnum(0, level, BufPtr, MaxLenPref, EntriesRead, TotalEntries, SV_TYPE_ALL, DomainName, ResumeHandle)
        If EntriesRead = 0 Then
            Return ans
        End If

        ' loop thru the entries
        num = 0
        ReDim ans(EntriesRead - 1)
        For i = 0 To EntriesRead - 1
            ' copy the stuff into our structure
            iPtr = New IntPtr(BufPtr.ToInt32 + (Marshal.SizeOf(ServerInfo) * i))
            ServerInfo = CType(Marshal.PtrToStructure(iPtr, GetType(SERVER_INFO_101)), SERVER_INFO_101)

            If filter = "" Or ServerInfo.sv101_name = filter.ToUpper Or ServerInfo.sv101_name Like filter.ToUpper Then
                ' add it to our string array
                ans(num) = ServerInfo.sv101_name
                num = num + 1
            End If

        If num > 0 Then
            ReDim Preserve ans(num - 1)
        End If
        Return ans
    End Function

    Function GetPCDomList(ByVal DomainName As String, Optional ByVal filter As String = "") As String()
        Dim dirs, dir As DirectoryEntry
        Dim ans(-1) As String
        Dim temp As New StringCollection

            dirs = New DirectoryEntry("WinNT://" & DomainName)
            For Each dir In dirs.Children
                ' collect data on all of our Domain PCs
                If dir.SchemaClassName = "Computer" Then
                    If filter = "" Or dir.Name = filter.ToUpper Or dir.Name Like filter.ToUpper Then
                        ' Add it to the list
                    End If
                End If
        End Try

        If temp.Count > 0 Then
            ReDim ans(temp.Count - 1)
            temp.CopyTo(ans, 0)
        End If
        Return ans
    End Function

    Public Function GetPCOUList(ByVal DomainName As String, ByVal OU_Name As String, ByVal Filter As String, ByVal Svr_Only As Boolean) As String()
        Dim entry, de As DirectoryEntry
        Dim srch As DirectorySearcher
        Dim result As SearchResult
        Dim ldap, buf, os, ans(-1) As String
        Dim temp As New StringCollection

            ldap = "LDAP://" & DomainName & "/" & OU_Name

            ' set our starting place to search
            entry = New DirectoryEntry(ldap)
            srch = New DirectoryServices.DirectorySearcher(entry)
            srch.Filter = "(ObjectCategory=computer)"

            ' OK, let's do it
            For Each result In srch.FindAll()
                de = result.GetDirectoryEntry

                buf = de.Properties("CN").Value
                If Filter = "" Or Filter.ToUpper = buf.ToUpper Or buf.ToUpper Like Filter.ToUpper Then
                    os = de.Properties("operatingSystem").Value
                    If Not IsNothing(os) Then
                        If Svr_Only = False Or (Svr_Only = True And os Like "*Server*") Then
                        End If
                    End If
                End If
        End Try

        If temp.Count > 0 Then
            ReDim ans(temp.Count - 1)
            temp.CopyTo(ans, 0)
        End If
        Return ans
    End Function
End Module

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

LVL 48

Expert Comment

ID: 16402324
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 400 total points
ID: 16402593
Here is a class that implements Net View for the domain.  There are fancier ways using ActiveDirectory, but this works even when you don't have ActiveDirectory.

Imports System.Diagnostics

Public Class NetView

  Public Shared Function GetDomainList(ByVal domain As String) As DataTable

    Dim proc As New Process
    proc.StartInfo.FileName = "net.exe"
    proc.StartInfo.Arguments = "view /domain:" & domain
    proc.StartInfo.RedirectStandardOutput = True
    proc.StartInfo.UseShellExecute = False
    proc.StartInfo.CreateNoWindow = True
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

    Dim output As String = proc.StandardOutput.ReadToEnd()

    Return ParseNames(output)

  End Function  'GetDomainList

  Private Shared Function ParseNames(ByVal input As String) As DataTable

    Dim table As New DataTable

    Dim text As New TextBox
    Dim withinBlock As Boolean
    text.WordWrap = False
    text.Text = input

    For Each line As String In text.Lines
      If withinBlock Then
        Dim position As Integer = line.IndexOf(" ")
        If position <> -1 AndAlso Not line.Equals("The command completed successfully.") Then
          Dim name As String = line.Substring(0, position).Trim()
          Dim value As String = line.Substring(position + 1).Trim()

          Dim row As DataRow = table.NewRow()
          row("Name") = name
          row("Value") = value
        End If
        withinBlock = line.StartsWith("Server Name")
      End If
    Next line

    Return table

  End Function  'ParseNames

End Class

LVL 96

Expert Comment

by:Bob Learned
ID: 16402605
  Me.ListBox1.DataSource = NetView.GetDomainList("domain")
  Me.ListBox1.DisplayMember = "Name"
  Me.ListBox1.ValueMember = "Value"


Author Comment

ID: 16403440
THanks for all the code and links!

In one of the links above, the following line caught my eye:

ds.Filter = "(objectClass=computer)"

Does this mean I can get other information about the computers too?  If I did want to get other information what kind of information can I get?  Also, can you get more information with the code posted by graye and TheLearnedOne?

Thanks for all the help.
LVL 41

Assisted Solution

graye earned 800 total points
ID: 16404682
Well, your ability to get more info is related to which technique you use...   For example, if you have an Active Directory domain, you can get a lot of information.   A typical entry for a computer in AD is (I redacted a bit):

      5> objectClass: top; person; organizationalPerson; user; computer;
      1> cn: MachineName;
      1> description: DPW OFC Emmet Gray, Bldg 4612;
      1> distinguishedName: CN=MachineName,OU=SomeOU,OU=Computers,DC=domain,DC=com;
      1> instanceType: 4;
      1> whenCreated: 4/18/2005 14:36:17 Central Standard Time Central Daylight Time;
      1> whenChanged: 3/31/2006 22:16:23 Central Standard Time Central Daylight Time;
      1> uSNCreated: 436426;
      1> uSNChanged: 7477403;
      1> name: MachineName;
      1> objectGUID: dee2444e-e2e9-43ae-8c4e-dccd75bac9c7;
      1> userAccountControl: 0x1020;
      1> codePage: 0;
      1> countryCode: 0;
      1> lastLogon: 3/31/2006 22:16:23 Central Standard Time Central Daylight Time;
      1> localPolicyFlags: 0;
      1> pwdLastSet: 3/29/2006 5:11:32 Central Standard Time Central Daylight Time;
      1> primaryGroupID: 515;
      1> objectSid: S-1-5-21-4101780369-38368224-130243791-192256;
      1> accountExpires: 65535/6/65535 14:0:64440 UNC;
      1> logonCount: 4;
      1> sAMAccountName: MachineName$;
      1> sAMAccountType: 805306369;
      1> operatingSystem: Windows XP Professional;
      1> operatingSystemVersion: 5.1 (2600);
      1> operatingSystemServicePack: Service Pack 2;
      1> dNSHostName: MachineName.domain.com;
      2> servicePrincipalName: HOST/MachineName; HOST/MachineName.domain.com;
      1> objectCategory: CN=Computer,CN=Schema,CN=Configuration,DC=domain,DC=com;
      1> isCriticalSystemObject: FALSE;
      5> dSCorePropagationData: 3/17/2006 13:51:55 Central Standard Time Central Daylight Time; 3/13/2006 11:26:25 Central Standard Time Central Daylight Time; 3/8/2006 9:50:41 Central Standard Time Central Daylight Time; 2/16/2006 14:22:41 Central Standard Time Central Daylight Time; 7/14/1601 17:36:49 Central Standard Time Central Daylight Time;

If you need a lot more, you can "probe" each PC on the LAN to get installed software, etc.  Let us know if you want to follow that idea...

Author Comment

ID: 16405163
That is fantastic!

If it's possible, I would like to know what software is installed on each pc and what hardware the PC has, e.g. processor, ram, harddrive etc etc

If that can be done, that would be amazing! :D

Author Comment

ID: 16405165
Yes we do have ActiveDirectory!
LVL 41

Expert Comment

ID: 16416337
I've got a program called SOSOS that does exactly that... it records 200 pieces of the information about the PC and then stores the info in  a database   The cool part about that is that you can then write queries against the database to answer questions, produces reports, etc

An introductory article and downloadable VB.Net source code is at http://home.hot.rr.com/graye/Articles/SOSOS.htm

Author Comment

ID: 16424797
Thanks for that link, but I can't seem to get it to work.  I have a new thread here which you might be able to answer?


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…

807 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