.Net Sockets

Y

yawnb

I am using VC++ .Net 2003 and have a question about putting a byte
array returned from a socket receivefrom method in to a struct.

Here is what I have:

Socket* s = 0;
Byte RecvBytes[] = new Byte[1500];

try {

IPEndPoint* endPoint = new IPEndPoint(IPAddress::Any, 1646);

s = new Socket(endPoint->Address->AddressFamily,
SocketType::Dgram, ProtocolType::Udp);
s->Bind(endPoint);
Console::WriteLine (S"Waiting to receive datagrams from client...");

IPEndPoint* sender = new IPEndPoint(IPAddress::Any, 0);
EndPoint* senderRemote = __try_cast<EndPoint*>(sender);

Int32 LengthBytes = s->ReceiveFrom(RecvBytes, 0,
RecvBytes->Length, SocketFlags::None, &senderRemote);

Console::WriteLine(S"Datagram Received from -> {0} {1} Bytes",
senderRemote->ToString(), Convert::ToString(LengthBytes));

I get a the RecvBytes byte array back and I want to put it in a
structure.

__gc struct auth_hdr {
Byte code;
Byte id;
UInt16 length;
Byte vector[];
Byte data[];
};

What is the best way to do it? I have tried to cast it like auth_hdr*
authhdr = reinterpret_cast<auth_hdr*>(RecvBytes) but it does
not work. Would it be better to try something like:

[StructLayout(LayoutKind::Explicit)]
public __gc class Packet
{
public:
[FieldOffset(0)] Byte Code;
[FieldOffset(1)] Byte ID;
[FieldOffset(2)] UInt16 Length;
[FieldOffset(20)] Byte Vector;
[FieldOffset(38)] Byte Data;
};
 
B

Bart Jacobs

Yawnb,

You can simply extract the header fields like so:

Byte code = RecvBytes[0];
Byte id = RecvBytes[1];

Extracting the length depends on whether it is encoded as little-endian
or big-endian.

Little-endian:

UInt16 length = BitConverter::ToUInt16(RecvBytes, 2);

Big-endian:

Byte lengthHigh = RecvBytes[2];
Byte lengthLow = RecvBytes[3];
UInt16 length = (lengthHigh << 8) | lengthLow;

Greetings

Bart Jacobs
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top