reading in C++ a socket open by Java + structure alignment

I am trying to write in Linnux a client in C++ using boost::asio data from a socket. The server is built in Java. The issue I have now is that I cannot read correctly some piece of information from the socket. If the client is done in JAVA everything is ok.

In details the big error I have are in receiving the unsigned long and the int in the structure below. I am expectng a value for anInteger should be 0x00000005 so 5, but reading from the socket gives me 0x03000 ( ?!?! ). It is definetely a different number and based on the hexadecimal printing I have less digits( ?!?!? ).

For aUnLong I should receive something approaching to a number 1279272977799 so in hex is 0x129DA9C8587 , instead a receive something like 0x00129ffffffdaffffff8fffffff9f5c . I see that some piece of information is good but it is mixed with all ff s and where I don't know where they come from.

I am guaranteed to receive each time 168 bytes ( so fixed number of bytes ). In the beginning I though about the data alignment of my structure so I introduced attribute (( packed )) .

The label and lbl_2 are string; I now that JAVA uses UTF but it is not clear to me how this play in this scenario.

Can you help me with this issue?

I thank you very much.

EO

union MyStruct
{
    char buffer[168];

    struct _data{
        char            dash[2];    
        unsigned long   aUnLong;
        char            label[128]; 
        char            lbl_2[24];  
        int         anInteger;  
    } __attribute__((__packed__));

    _data data; // the real data
};

Reading happens using this simple line

MyStruct obj;
size_t reply_length = asio::read( s,asio::buffer(obj.buffer, 168));

this is the original format sent out

byte 000,001: #
byte 002-010: aLong (8 byte) long - milliseconds since 1-1-1970 in UTC
byte 011-139: label (128 byte 2byte per character) label_1
byte 140-164: lbl2 (24 byte 2byte per character) label2 code
byte 165-169: anInteger (4 byte) integer

Your structure doesn't appear to be 168 bytes on common systems. If long is 4 bytes (typical in 32-bit compilation) then your struct is probably 162 or 164 if packed isn't honored. If long is 8 bytes, then 164 or 168 (if padded, which as you surmise is bad).

Check the sizeof(_data) in your program and see what the compiler tells you it is.

Also, your original format information is confusing. For example you say "byte 002-010: aLong (8 byte) long", but bytes 2-10 are NINE (9) bytes not 8. Is there a crc or checksum byte?

链接地址: http://www.djcxy.com/p/61898.html

上一篇: 将大端结构转换成小端

下一篇: 在C ++中读取由Java +结构对齐打开的套接字