The DsAddressToSiteNamesEx function obtains the site and subnet names corresponding to the addresses specified.
Sample usage: How to get the site and subnet names from an IP Address of a machine
[DllImport("Netapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsAddressToSiteNamesEx", CharSet = CharSet.Unicode)] private static extern int DsAddressToSiteNamesEx( [In] string computerName, [In] Int32 EntryCount, [In] SOCKET_ADDRESS[] SocketAddresses, [Out] out IntPtr SiteNames, [Out] out IntPtr SubnetNames); [DllImport("Netapi32.dll")] private static extern int NetApiBufferFree([In] IntPtr buffer); private const int ERROR_SUCCESS = 0; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SockAddr_In { public Int16 sin_family; public Int16 sin_port; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public byte[] sin_addr; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] sin_zero; } [StructLayout(LayoutKind.Sequential)] internal struct SOCKET_ADDRESS { public IntPtr lpSockaddr; public Int32 iSockaddrLength; } static void Main(string[] args) { string sIP = "10.251.50.101";//@ip = 10.251.50.101 string sDC = "dc-fr-001";//the name of a domain controller IntPtr pSiteNames; IntPtr pSubnetNames; SOCKET_ADDRESS[] SocketAddresses = new SOCKET_ADDRESS[1]; String[] ipArray = sIP.Split('.'); SockAddr_In sockAddr; sockAddr.sin_family = 2; sockAddr.sin_port = 0; sockAddr.sin_addr = new byte[4] { byte.Parse(ipArray[0]), byte.Parse(ipArray[1]), byte.Parse(ipArray[2]), byte.Parse(ipArray[3]) }; sockAddr.sin_zero = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 }; SocketAddresses[0].iSockaddrLength = Marshal.SizeOf(sockAddr); IntPtr pSockAddr = Marshal.AllocHGlobal(16); Marshal.StructureToPtr(sockAddr, pSockAddr, true); SocketAddresses[0].lpSockaddr = pSockAddr; if (DsAddressToSiteNamesEx( sDC, 1,//EntryCount SocketAddresses, out pSiteNames, out pSubnetNames) == ERROR_SUCCESS) { string sSite = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(pSiteNames, 0)); string sSubnet = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(pSubnetNames, 0)); Console.WriteLine("Found site: " + sSite); Console.WriteLine("Found subnet: " + sSubnet); NetApiBufferFree(pSubnetNames); NetApiBufferFree(pSiteNames); } }
Recent Comments