PDA

View Full Version : [Solved] QHostAddress and QByteArray question



RossenD
30th May 2012, 10:24
Hello,
Here come piece of code


ba = sock->read(4);
QHostAddress addr((quint32)ba.constData());
thisHost = addr.toString();

Any idea why if ba contain 174.194.35.191 ( google IP for example ) addr is 11.25.48.176? What is wrong here?

wysota
30th May 2012, 10:31
Network/host byte order mismatch?

Cruz
30th May 2012, 10:32
Because constData() returns a char * that you cast to quint32 and the QHostAddress thinks it's an ip address, though it's just the memory address of a char.

RossenD
30th May 2012, 10:54
Because constData() returns a char * that you cast to quint32 and the QHostAddress thinks it's an ip address, though it's just the memory address of a char.

:) You mind that cast actually cast char * value not char *?


Network/host byte order mismatch?

Hm...To swap bytes before cast?

Cruz
30th May 2012, 11:15
quint32 bad = (quint32)ba.constData();


bad now contains the physical memory address of the first byte of the QByteArray ba. It's not the content of the first byte, it's the address of the first byte.
If you pass this as an argument like QHostAddress(bad), then you have created a network address from a memory address. It is of course not the address, that ba contains.

RossenD
30th May 2012, 11:25
It's not the content of the first byte, it's the address of the first byte.

Ok, so how to cast content, not address of the first byte?

wysota
30th May 2012, 11:58
What does the byte array actually contain? What exactly did you write to the socket?

RossenD
30th May 2012, 15:11
Case solved :)


quint32 uiAddress;
memcpy( &uiAddress, ba.constData(), 4);
QHostAddress addr( uiAddress);