C# – Enumerate all online computers on LAN

I am writing a small tool to send file over local area network. Sometimes I would like to exchange some files between computers. You may be ask me why I do not setup any home network and simply share file between computers. The reason is I am lazy. You must tell me that I am crazy. I know. I am lazy to set up network but spend time to write a tool which may be useless for others. I can not understand myself why I do that. Ok it time to end chatting. Go back to the source code. In my “stolen” source code, I just call a native API function NetServerEnum to enumerate all computers.

[DllImport("netapi32.dll", EntryPoint = "NetServerEnum")]
        public static extern int NetServerEnum([MarshalAs(UnmanagedType.LPWStr)]string servername,
           int level,
           out IntPtr bufptr,
           int prefmaxlen,
           ref int entriesread,
           ref int totalentries,
           SV_101_TYPES servertype,
           [MarshalAs(UnmanagedType.LPWStr)]string domain,
           IntPtr resume_handle);

For more details on porting this API function from c++ to c# you can download NetApi in C# source code. From the source code file you can use the function GetServerList which returns the ArrayList of SERVER_INFO_101 structs to Enumerate all the servers on a domain or workgroup.

       ArrayList alNetworkComputers = NetApi32.GetServerList(NetApi32.SV_101_TYPES.SV_TYPE_WORKSTATION | NetApi32.SV_101_TYPES.SV_TYPE_SERVER);

            for (int nIndex = 0; nIndex < alNetworkComputers.Count; nIndex++)
            {
                Console.WriteLine(((NetApi32.SERVER_INFO_101)alNetworkComputers[nIndex]).sv101_name);
            }

I think this post is not very interesting, but I think it may be useful for someone who needs it.

UPDATE 18.10.2011
– List all computers with his name and ip addresses.

ArrayList alNetworkComputers = NetApi32.GetServerList(NetApi32.SV_101_TYPES.SV_TYPE_WORKSTATION | NetApi32.SV_101_TYPES.SV_TYPE_SERVER);
string computerName = "";
for (int nIndex = 0; nIndex < alNetworkComputers.Count; nIndex++)
{
	computerName = ((NetApi32.SERVER_INFO_101)alNetworkComputers[nIndex]).sv101_name;
	Console.WriteLine(Dns.GetHostAddresses(computerName)[0].ToString() + "\t\t : \t" + computerName);
}
Console.ReadLine();

2 thoughts on “C# – Enumerate all online computers on LAN”

  1. He he, lâu quá không có dịp trao đổi với lão rồng 😀 Lang thang tìm cái code này để làm cái tool manager pc on LAN 😀

    (TheShinichi on Rea forum)

  2. Thank you! I was looking for something exactly like this and have been banging my head against the wall for days. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *