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();