在C#中查询DHCP服务器

时间:2010-02-08 21:07:05

标签: c# windows dhcp netsh dhcpobjs

我需要通过服务器本身运行的程序或者最好通过在其中一个DHCP客户端上运行的程序,将MAC映射到DHCP服务器上的IP。

我理解netsh utility可用于获取转储,但我没有取得多大成功。

任何有效的例子或提示?

我拥有DHCP服务器的管理员权限

修改

我不想使用arp缓存,因为这需要我广播ping(在Windows上不允许)或ping所有可能的子网IP地址(这需要很多时间)。

我确信DHCP服务器存储MAC到IP的映射,如何使用该信息,将MAC映射到IP地址?

3 个答案:

答案 0 :(得分:4)

您可以使用 Windows 2000 Resource Kit 中的 DHCP Objects组件。尽管该组件很难找到,但是对于Windows 2000而言,根据微软的说法,它在2010年7月失去了生命支持并且文档很少,它确实有效。

  1. 如果您在Microsoft找不到,请从例如here下载名为 DHCP Objects 的资源工具包工具。这将为您提供一个.exe文件,该文件将安装DHCP Objects组件。
  2. 使用DHCPOBJS.DLL 注册regsvr32文件或为其创建COM +应用程序。哪个适用取决于COM组件将如何在您的系统上使用。
  3. 使用类型库导入器tlbimp.exe创建一个围绕DHCPOBJS.DLL的托管包装器,现在它已由系统注册。
  4. 在Visual Studio中,添加对托管包装器的引用。其默认生成的名称为DhcpObjects.dll
  5. 现在你可以针对组件编写这样的代码:

    using DhcpObjects;
    class Program {
        static void Main(string[] args) {
            var manager = new Manager();
            var server = dhcpmgr.Servers.Connect("1.2.3.4");
            // query server here
        }
    }
    

    安装程序还提供Windows帮助文件,其中包含有关如何查询和操作DHCP服务器的更多文档。 “对象模型”部分非常有用。

答案 1 :(得分:1)

using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Net;

namespace dhcp
{
// c# class for processed clients

public class dhcpClient
{
    public string hostname { get; set; }
    public string ip       { get; set; }
    public string mac      { get; set; }
}

// structs for use with call to unmanaged code

[StructLayout(LayoutKind.Sequential)]
public struct DHCP_CLIENT_INFO_ARRAY
{
    public uint NumElements;
    public IntPtr Clients;
}

[StructLayout(LayoutKind.Sequential)]
public struct DHCP_CLIENT_UID
{
    public uint DataLength;
    public IntPtr Data;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DHCP_CLIENT_INFO
{
    public uint ip;
    public uint subnet;

    public DHCP_CLIENT_UID mac;

    [MarshalAs(UnmanagedType.LPWStr)]
    public string ClientName;

    [MarshalAs(UnmanagedType.LPWStr)]
    public string ClientComment;
}

// main

class Program
{
    static void Main()
    {
        try
        {
            // get settings

            String server, subnet;

            Console.Write("Enter server : ");
            server = Console.ReadLine();
            Console.Write("Enter subnet : ");
            subnet = Console.ReadLine();

            // gather clients

            ArrayList clients = findDhcpClients(server, subnet);

            // output results

            Console.WriteLine();

            foreach (dhcpClient d in clients)
                Console.WriteLine(String.Format("{0,-35} {1,-15} {2,-15}", d.hostname, d.ip, d.mac));

            Console.WriteLine('\n' + clients.Count.ToString() + " lease(s) in total");
        }

        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.ReadLine();
    }

    static ArrayList findDhcpClients(string server, string subnet)
    {
        // set up container for processed clients

        ArrayList foundClients = new ArrayList();

        // make call to unmanaged code

        uint parsedMask     = StringIPAddressToUInt32(subnet);
        uint resumeHandle   = 0;
        uint numClientsRead = 0;
        uint totalClients   = 0;

        IntPtr info_array_ptr;

        uint response = DhcpEnumSubnetClients(
            server,
            parsedMask,
            ref resumeHandle,
            65536,
            out info_array_ptr,
            ref numClientsRead,
            ref totalClients
            );

        // set up client array casted to a DHCP_CLIENT_INFO_ARRAY
        // using the pointer from the response object above

        DHCP_CLIENT_INFO_ARRAY rawClients =
            (DHCP_CLIENT_INFO_ARRAY)Marshal.PtrToStructure(info_array_ptr, typeof(DHCP_CLIENT_INFO_ARRAY));

        // loop through the clients structure inside rawClients 
        // adding to the dchpClient collection

        IntPtr current = rawClients.Clients;

        for (int i = 0; i < (int)rawClients.NumElements; i++)
        {
            // 1. Create machine object using the struct

            DHCP_CLIENT_INFO rawMachine =
                (DHCP_CLIENT_INFO)Marshal.PtrToStructure(Marshal.ReadIntPtr(current), typeof(DHCP_CLIENT_INFO));

            // 2. create new C# dhcpClient object and add to the 
            // collection (for hassle-free use elsewhere!!)

            dhcpClient thisClient = new dhcpClient();

            thisClient.ip = UInt32IPAddressToString(rawMachine.ip);

            thisClient.hostname = rawMachine.ClientName;

            thisClient.mac = String.Format("{0:x2}{1:x2}.{2:x2}{3:x2}.{4:x2}{5:x2}",
                Marshal.ReadByte(rawMachine.mac.Data),
                Marshal.ReadByte(rawMachine.mac.Data, 1),
                Marshal.ReadByte(rawMachine.mac.Data, 2),
                Marshal.ReadByte(rawMachine.mac.Data, 3),
                Marshal.ReadByte(rawMachine.mac.Data, 4),
                Marshal.ReadByte(rawMachine.mac.Data, 5));

            foundClients.Add(thisClient);

            // 3. move pointer to next machine

            current = (IntPtr)((int)current + (int)Marshal.SizeOf(typeof(IntPtr)));
        }

        return foundClients;
    }

    public static uint StringIPAddressToUInt32(string ip)
    {
        // convert string IP to uint IP e.g. "1.2.3.4" -> 16909060

        IPAddress i = System.Net.IPAddress.Parse(ip);
        byte[] ipByteArray = i.GetAddressBytes();

        uint ipUint = (uint)ipByteArray[0] << 24;
        ipUint += (uint)ipByteArray[1] << 16;
        ipUint += (uint)ipByteArray[2] << 8;
        ipUint += (uint)ipByteArray[3];

        return ipUint;
    }

    public static string UInt32IPAddressToString(uint ip)
    {
        // convert uint IP to string IP e.g. 16909060 -> "1.2.3.4"

        IPAddress i = new IPAddress(ip);
        string[] ipArray = i.ToString().Split('.');

        return ipArray[3] + "." + ipArray[2] + "." + ipArray[1] + "." + ipArray[0];
    }

    [DllImport("dhcpsapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern uint DhcpEnumSubnetClients(
            string ServerIpAddress,
            uint SubnetAddress,
        ref uint ResumeHandle,
            uint PreferredMaximum,
        out IntPtr ClientInfo,
        ref uint ElementsRead,
        ref uint ElementsTotal
    );
}
}

答案 2 :(得分:0)

使用arp -a使用诀窍......在我的机器上,我得到的输出是:

我将mac / ip地址替换为伪造值以显示结果......

C:\Documents and Settings\Tom>arp -a

Interface: 10.203.24.196 --- 0xf0007
  Internet Address      Physical Address      Type
  10.203.24.198         02-50-f3-10-14-06     dynamic

C:\Documents and Settings\Tom>

通过使用System.Diagnostics.Process进行炮轰,您可以将输出重定向到输入流并从中读取...

希望这有帮助, 最好的祝福, 汤姆。