Get List of Network Computer Names in C#

In this article, I am going to write C# code to get a list of network computer names using NetServerEnum API function and get a list of Active Directory-based network computer names using DirectoryService.

Summary

Get List of Computer Names in current Network using C#

You can easily list all the available computers in the current network by using the 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 returned in the results by using the parameter servertype. You can refer to 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: The below C# code requires the “Computer Browser” Windows service to be installed and running state.

In Win10 v1709 and later versions, the SMBv1 client/server component (which includes the Computer Browser service) is an optional component, and it is no longer installed by default. The SMBv1 client component will be automatically removed after 15 days if the OS detects they are not being used. For more details, see this post : SMBv1/Computer Browser Service (Missing) is not installed by default.

To install the Computer Browser service (SMBv1 server/client components), open the Control Panel -> Programs -> Turn Windows Features On or Off -> scroll down and select SMB 1.0/CIFS File Sharing Support and click OK. Finally, restart the machine and check the service.

Install and enable the Computer Browser service/SMBv1 feature

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();
            if (networkComputers.Count > 0)
            {
                foreach (string computerName in networkComputers)
                {
                    Console.WriteLine(computerName);
                }
            }
            else
            {
                Console.BackgroundColor = ConsoleColor.DarkYellow;
                Console.ForegroundColor = ConsoleColor.Black;
                Console.WriteLine("No computers found");
                Console.WriteLine("##########");
                Console.WriteLine("Ensure the 'Computer Browser' Windows Service is available and running.");
                Console.WriteLine("##########");
                Console.WriteLine("In Win10 v1709 and later versions, the SMBv1 server components (which include the Computer Browser service) are not installed by default, and the SMBv1 'Client' components will be automatically removed after 15 days if the OS detects they are not being used.");
                Console.WriteLine("##########");
                Console.WriteLine("To enable the Computer Browser service, open the Control Panel -> Programs ->  Turn Windows Features On or Off -> scroll down and select SMB 1.0/CIFS File Sharing Support and click OK. Finally, restart the machine and check the service.");
                Console.WriteLine("##########");
                Console.WriteLine("https://docs.microsoft.com/en-US/windows-server/storage/file-server/troubleshoot/smbv1-not-installed-by-default-in-windows");
                Console.WriteLine("##########");

                Console.BackgroundColor = ConsoleColor.Black;
                Console.ForegroundColor = ConsoleColor.White;

            }
            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 the above code to get a list of computers in the local 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.Length > 1 ? ipAddresses[1] : ipAddresses[0];

        string ipAdress = ip.ToString();

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

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

If you are trying to list the available computer names in the 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


Advertisement