Tuesday, 15 April 2014

Get List of Network Computer Names in C#

Description:

In this article, I am going write C# code to Get List of Network Computer Names using NetServerEnum API function and Get List of Active Directory based Network Computer Names in C# using DirectoryService.

Summary:


Get List of Computer Names in current Network using C#

You can easily list all the available computers in current network by using NetServerEnum API function. NetServerEnum function lists all servers of the specified type that are visible in a domain. You can specify what type of computers should be return in the results by using the parameter servertype. You can refer this article http://msdn.microsoft.com/en-us/library/windows/desktop/aa370623(v=vs.85).aspx to know about the structure of NetServerEnum and possible enum values of servertype.

Note: If your network uses Active Directory to authenticate , the Computer Browser Windows service must be running to get computers in Active Directory domain network.

       1 - Go to Control Panel > Administrative Tools > Services.
       2 - Double-click Computer Browser to open the Properties dialog box.
       3 - Set the Startup type to Automatic.
       4 - Click Start.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;

namespace MorganUtil
{
    class Program
    {
        //declare the Netapi32 : NetServerEnum method import
        [DllImport("Netapi32", CharSet = CharSet.Auto,
        SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]

        // The NetServerEnum API function lists all servers of the 
        // specified type that are visible in a domain.
        public static extern int NetServerEnum(
            string ServerNane, // must be null
            int dwLevel,
            ref IntPtr pBuf,
            int dwPrefMaxLen,
            out int dwEntriesRead,
            out int dwTotalEntries,
            int dwServerType,
            string domain, // null for login domain
            out int dwResumeHandle
            );

        //declare the Netapi32 : NetApiBufferFree method import
        [DllImport("Netapi32", SetLastError = true),
        SuppressUnmanagedCodeSecurityAttribute]
        
        // Netapi32.dll : The NetApiBufferFree function frees 
        // the memory that the NetApiBufferAllocate function allocates.         
        public static extern int NetApiBufferFree(
            IntPtr pBuf);

        //create a _SERVER_INFO_100 STRUCTURE
        [StructLayout(LayoutKind.Sequential)]
        public struct _SERVER_INFO_100
        {
            internal int sv100_platform_id;
            [MarshalAs(UnmanagedType.LPWStr)]
            internal string sv100_name;
        }

        static void Main(string[] args)
        {
            List<string> networkComputers = GetNetworkComputerNames();
            foreach (string computerName in networkComputers)
            {
                Console.WriteLine(computerName);
            }
            Console.ReadLine();
        }

        private static List<string> GetNetworkComputerNames()
        {
            List<string> networkComputerNames = new List<string>();
            const int MAX_PREFERRED_LENGTH = -1;
            int SV_TYPE_WORKSTATION = 1;
            int SV_TYPE_SERVER = 2;
            IntPtr buffer = IntPtr.Zero;
            IntPtr tmpBuffer = IntPtr.Zero;
            int entriesRead = 0;
            int totalEntries = 0;
            int resHandle = 0;
            int sizeofINFO = Marshal.SizeOf(typeof(_SERVER_INFO_100));

            try
            {
                int ret = NetServerEnum(null, 100, ref buffer,
                    MAX_PREFERRED_LENGTH,
                    out entriesRead,
                    out totalEntries, SV_TYPE_WORKSTATION |
                    SV_TYPE_SERVER, null, out 
                    resHandle);
                //if the returned with a NERR_Success 
                //(C++ term), =0 for C#
                if (ret == 0)
                {
                    //loop through all SV_TYPE_WORKSTATION and SV_TYPE_SERVER PC's
                    for (int i = 0; i < totalEntries; i++)
                    {
                        tmpBuffer = new IntPtr((int)buffer +
                                   (i * sizeofINFO));

                    //Have now got a pointer to the list of SV_TYPE_WORKSTATION and SV_TYPE_SERVER PC's
                        _SERVER_INFO_100 svrInfo = (_SERVER_INFO_100)
                            Marshal.PtrToStructure(tmpBuffer,
                                    typeof(_SERVER_INFO_100));

                        //add the Computer name to the List
                        networkComputerNames.Add(svrInfo.sv100_name);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //The NetApiBufferFree function frees the allocated memory
                NetApiBufferFree(buffer);
            }

            return networkComputerNames;
        }
    }
}


Get IP Address of all Computers in Current Network using C#

You can use .NET classes Dns and IPAddress to convert Hostname into IP Address in C#. Get function reference GetNetworkComputerNames from above code to get list of computers in local network.

Note: If your network uses Active Directory to authenticate , the Computer Browser Windows service must be running to get computers in Active Directory domain network.
static void Main(string[] args)
        {
            // GetNetworkComputerNames - use above code to get list of network computers
            List<string> networkComputers = GetNetworkComputerNames();
            foreach (string computerName in networkComputers)
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(computerName);

                IPAddress ip = ipAddresses[1];

                string ipAdress = ip.ToString();

                Console.WriteLine(ipAdress);
            }
            Console.ReadLine();
        }

Get List of Computer Names in AD based Network using C#

If you are trying list the available computer names in Active Directory based domain Network, you can use System.DirectoryService namespace to get computer names.
using System;
using System.DirectoryServices;

namespace MorganUtil
{
    class Program
    {
        static void Main(string[] args)
        {
             DirectoryEntry root = new DirectoryEntry("WinNT:");
            foreach (DirectoryEntry obj in root.Children)
            {
                foreach (DirectoryEntry computer in obj.Children)
                {
                    if (computer.SchemaClassName.Equals("Computer"))
                    {
                        Console.WriteLine(computer.Name);
                    }
                }
            }

            Console.ReadLine();
        }
    }
}

Thanks,
Morgan
Software Developer

Advertisements
Advertisements

5 comments:

  1. Many thanks for a code!
    Change a line in "Get IP Address of all Computers in Current Network using C#":
    IPAddress ip = ipAddresses[0];

    ReplyDelete
  2. not working for me, the console windows keeps black and nothing appears

    ReplyDelete
    Replies
    1. Hi oscar, If your network uses Active Directory to authenticate , the Computer Browser Windows service must be running to get computers in Active Directory domain network.

      1 - Go to Control Panel > Administrative Tools > Services.

      2- Double-click Computer Browser to open the Properties dialog box.

      3- Set the Startup type to Automatic.

      4- Click Start.

      Delete
  3. The code for 'Get List of Computer Names in AD based Network using C#' is also returning AD users and groups. Any idea why?

    And thanks so much for your GetNetworkComputerNames method; it's fast and working perfectly for me.

    ReplyDelete
    Replies
    1. Sorry, it was my mistake, now I have updated the code.
      Put this condtion 'if (computer.SchemaClassName.Equals("Computer"))' to get only computers

      Delete