I am currently building a DHCPMessage class in c#.
RFC is available here : http://www.faqs.org/rfcs/rfc2131.html
Pseudo
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;
}
If we imagine that each field is a fixed length bit array, what is :
- The most versitile
- Best practice
way of r开发者_C百科epresenting this as a class???
OR.. how would you write this? :)
For starters, you might try the BitArray class. No need to reinvent the wheel here.
If you're worried about it taking up too much space/memory, don't be. Just initialize it to the right size:
BitArray op = new BitArray(8);
(The above will hold 8 bits and should take up 1 byte)
You are on the wrong track with this, it isn't a bit vector. The message is defined in "octets", better known as "bytes". An equivalent C# declaration that you can use with Marshal.PtrToStructure is:
[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;
}
You'll need to handle the variable length options field separately.
Are you sure you want to be using bit arrays for some of these? For example, you can use byte for 8 bits, int for 32 bits, and byte arrays for pieces that map to null terminated strings like 'sname' for example. Then you can use simple bitwise operators (&, |) to check/manipulate the bits.
Here are some posts I did on converting TCP header to a structure, which also covers endianness etc.
http://taylorza.blogspot.com/2010/04/archive-structure-from-binary-data.html http://taylorza.blogspot.com/2010/04/archive-binary-data-from-structure.html
These are quite old, I migrated them from my old blog just so they do not get lost.
精彩评论