Parse binary data for c# bootp server?
I need one of my C# .NET applications to act as a bootp server. The protocol is pretty simple but I dont know an easy way to build/parse the binary data.
开发者_如何学运维Any ideas:
(source: tcpipguide.com)You can create a simple structure like:
[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
}
and use the code from this blogpost to serialize/deserialize packets. But there may be a problem with ServerName and BootFilename because of differences in encoding and probably you need to specify exact FieldOffset for each of the fields (see this topic on msdn for details).
Hope this will help :)
There's a couple ways to do this. You might be able to play around with the marshaling attributes such as StructLayout to pack a structure into a byte array but this is probably tricky and not worth the effort.
You could use a specialized framework such as Protobuf to attribute a class in such a way that it will be serialized to match the structure you need.
But in my experience, the easiest, fastest, and most flexible method of creating a binary structure like this is to use a MemoryStream class to hold a buffer of byes, then use a BinaryWriter around it to actually write the binary data into the stream.
In any case, it helps to have a working server to reference. Use a tool like Wireshark or Microsoft Network Monitor to capture the wire traffic so you can compare your wire format to an example that is known to work.
精彩评论