How to construct a request message with a given message specification, and then send to server thought c socket? Binary protocol is employed for Client and Server communication. Are the following approaches correct?
Given message specification:
Field Fomat Length values ------------ ------ ------ -------- requesID Uint16 2 20 requestNum Uint16 2 100 requestTitle String 10 data sring
/************** approach 1 ****************/ typedef unsigned short uint16; typedef struct { uint16 requesID [2]; uint16 requestNum [2]; unsigned char requestTitle [10]; }requesMsg; … requesMsg rqMsg; memcpy(rqMsg.requesID, "\x0\x14", 2); //20 memcpy(rqMsg.requesNum, "\x0\x64", 2); //100 memcpy(rqMsg.requesTitle, "title01 ", 10); … send(sockfd, &rqMsg, sizeof(rqMsg), 0); /************** approach 2 ****************/ unsigned char rqMsg[14]; memset(rqMsg, 0, 14); memcpy(rqMsg, "\x0\x14", 2); memcpy(rqMsg+2, "\x0\x64", 2); memcpy(rqMsg+4, "title01 ", 10); … send(sock, &rqMsg, sizeof(rqMsg), 0);
memset
call yourself. – Kerrek SBpragma pack(1)
for the structure he could get the correct result. (Ok, as soon as he removes the array size from the fields) But unfortunately the code is not really portable then... – junix