解析c#bootp服务器的二进制数据?

时间:2010-02-10 16:35:08

标签: c# binary binary-data bootp

我需要一个C#.NET应用程序充当bootp服务器。该协议非常简单,但我不知道构建/解析二进制数据的简单方法。

任何想法: alt text http://www.tcpipguide.com/free/diagrams/bootpformat.png

2 个答案:

答案 0 :(得分:2)

您可以创建一个简单的结构,如:

[Serializable]
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct MyData {
    public byte OpCode;
    public byte HardwareType;
    public byte HardwareAddressType;
    public byte Hops;

    public int TransactionId;

    public short Seconds;
    public short Flags;

    public int ClientIPAddress;

    public int CurrentIP;

    // all other fields in the required sequence  
}  

并使用this blogpost中的代码来序列化/反序列化数据包。但是由于编码的不同,ServerName和BootFilename可能存在问题,您可能需要为每个字段指定确切的FieldOffset(有关详细信息,请参阅this topic on msdn)。 希望这会有所帮助:)

答案 1 :(得分:1)

有几种方法可以做到这一点。您可以使用诸如StructLayout之类的marshaling attributes来将结构打包到字节数组中,但这可能很棘手且不值得付出努力。

您可以使用Protobuf这样的专门框架来定义类,使其序列化以匹配您需要的结构。

但根据我的经验,创建像这样的二进制结构的最简单,最快速,最灵活的方法是使用MemoryStream类来保存byes的缓冲区,然后在它周围使用BinaryWriter来实际写入将二进制数据导入流中。

无论如何,有一个工作服务器可供参考。使用Wireshark或Microsoft Network Monitor等工具捕获线路流量,以便将线路格式与已知可用的示例进行比较。