QUdpSocket and ntohl()
-
Hi,
I am trying to do something trivial , but I am not able to achieve the desired output.I have coded a small Qt(on Windows-64bit) UDP Reciever program, that is receiving messages from pure 32bit- Linux Udp Client.
I do not know if I need ntohl() and htonl() here. I have tried sending integer part of information from Linux
using htonl() and also without it. In both cases the received integers are garbage, and so is the data in char-array.The code looks something like this:
Linux(32bit):
@
struct sMsg_t {
unsigned int a;
unsigned int b;
unsigned int c;
unsigned int len_of_data;
char data[1400];
};
@Windows(64bit):
@
struct sMsg_t {
quint32 a;
quint32 b;
quint32 c;
quint32 len_of_data;
char data[1400];
};void UdpReader::readPendingDatagram()
{
while(sock_reader.hasPendingDatagrams())
{
sMsg_t m;
int len = sizeof(m);
sock_reader.set
sock_reader.readDatagram(reinterpret_cast<char*>&m, len);
// =================
// Here i print the values, they are NOT correct. How can I fix it?
//
}
}@Thanks in Advance.
-
It is a good practice to use hton/ntoh functions when you sending binary data through the network.
Before sending data you need to serialize them and then deserialize when you received the data.
It is your responsibility unless you are using some third party protocol implementation.
How do you send data? -
yes, I am programming both ends (Linux and Windows). I have serialized using htonl() on Linux, but not done anything similar on Qt side. I am sending data from Linux using sockets (sendto())
This is what my Linux PC App function looks like:
@
send_msg(sMsg_t buff, int a, int b, int c){
buff->a = htonl(a);
buff->b = htonlb);
buff->c = htonl(c);
buff->length_of_data = htonl(0);
sendto(sendfd, reinterpret_cast<char>(&buff) , sizeof(sMsg_t), 0 , 0, sizeof(struct sockaddr_in));
}
@ -
When you received sMsg_t m on Qt side did you try to print it with using ntohl() for the integer members ?
-
Unless that's a typo, buff is already a pointer, so you should have @reinterpret_cast<char*>(buff) @
instead of
@reinterpret_cast<char*>(&buff) @in the sendto call.
-
Thanks Alex! That was the actual bug.