Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

delphi - How to convert a record from host to network byte order (big endian)?

I have a record:

  Tconnecting = record
  var
    a: int64;
    b: integer;
    c: integer;
  end;

which I need send to server using UDP protocol

I fill it

  packet.a := StrToInt64('0x1234567890');
  packet.b := 0;
  packet.c := RandomRange(1, 9999999);

and sending it

  SetLength(send_data, sizeof(packet));
  send_data := RawToBytes(packet, SizeOf(packet));
  udp.SendBuffer(make_it_big_endian(send_data)); <-- the question... "network byte order"

or maybe I'm doing something wrong? I need to send "bign endian" packet

pack("N*", int64, int, int); (this is in PHP)

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you are actually doing is converting from host byte order to network byte order. All standard sockets libraries provide helper functions to do that.

For example, Winsock offers htons, htonl etc. And in the opposite direction you have ntohs, ntohl etc. If you are using Indy, then the equivalent functions are GStack.HostToNetwork and GStack.NetworkToHost.

You should serialize each field into a byte stream, with each field being transformed by the appropriate hton* function. Then you can put the byte stream on the wire.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...