1

我目前正在 c# 中构建一个 DHCPMessage 类。

RFC 可在此处获得:http: //www.faqs.org/rfcs/rfc2131.html

public object DHCPMessage
{
    bool[8] op;
    bool[8] htype;
    bool[8] hlen;
    bool[8] hops;
    bool[32] xid;
    bool[16] secs;
    bool[16] flags;
    bool[32] ciaddr;
    bool[32] yiaddr;
    bool[32] siaddr;
    bool[32] giaddr;
    bool[128] chaddr;
    bool[512] sname;
    bool[1024] file;
    bool[] options;
}

如果我们想象每个字段都是一个固定长度的位数组,那么:

  1. 最万能的
  2. 最佳实践

将其表示为一个类的方式???

或者..你会怎么写这个?:)

4

3 回答 3

11

对于初学者,您可以尝试BitArray类。无需在这里重新发明轮子。

如果您担心它占用太多空间/内存,请不要担心。只需将其初始化为正确的大小:

BitArray op = new BitArray(8);

(以上将保持 8 位,应占用 1 字节)

于 2010-04-19T17:00:46.950 回答
4

你在错误的轨道上,它不是一个位向量。消息以“字节”定义,也就是众所周知的“字节”。可以与 Marshal.PtrToStructure 一起使用的等效 C# 声明是:

    [StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
    struct DHCPMessage {
        public byte op;
        public byte htype;
        public byte hlen;
        public byte hops;
        public uint xid;
        public ushort secs;
        public ushort flags;
        public uint ciaddr;
        public uint yiaddr;
        public uint siaddr;
        public uint giaddr;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)]
        public byte[] chaddr;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=64)]
        public string sname;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
        public string file;
    }

您需要单独处理可变长度选项字段。

于 2010-04-19T17:39:57.777 回答
2

您确定要对其中一些使用位数组吗?例如,您可以将 byte 用于 8 位,将 int 用于 32 位,并将字节数组用于映射到 null 终止字符串(例如,“sname”)的片段。然后,您可以使用简单的按位运算符(&、|)来检查/操作位。

这是我在将 TCP 标头转换为结构时所做的一些帖子,其中还包括字节序等。

http://taylorza.blogspot.com/2010/04/archive-structure-from-binary-data.html http://taylorza.blogspot.com/2010/04/archive-binary-data-from-structure.html

这些已经很老了,我从我的旧博客中迁移了它们,这样它们就不会迷路。

于 2010-04-19T17:14:13.963 回答