I have a struct defined as follow:
struct controlMessage
{
struct iphdr cmIphdr; //this use ip.h fronm linux library
struct ipPayload cmIpPayload;
};
struct ipPayload
{
uint8_t mType;
uint16_t cid;
char* payload; //this is intended to send different size of content
}
Then the sender will set up the struct and send the controlMessage to receiver
struct controlMessage *cMsg = (struct controlMessage*) malloc (sizeof(struct controlMessage);
cMsg->cmIphdr.protocol = 200; //this is not important, could be any number
//etc wth all the other fields in iphdr
//My question is in the ipPayload struct
cMsg->cmIpPayload.mType = 82; //this is fine
cMsg->cmIpPayload.cid = 1; //this is fine
//Now I want to point my char pointer to a struct and send it as content
struct controlMsg_payload
{
uint16_t somePort;
//will be more stuffs, but keep it 1 for now for simplicity
}
struct controlMsg_payload *payload = (struct controlMsg_payload*) malloc(sizeof(struct controlMsg_payload));
payload->somePort = 1000; //just assign a static number to it
cMsg->cmIpPayload.payload = (char*) payload; //not sure if i did it right
//Now sends it using sendto
data = sendto(sockfd, cMsg, sizeof(struct controlMessage), 0, (struct sockaddr*) &rcv_addr, sizeof(rcv_addr));
//remove error check for simplicity
I'm not sure if I send it correctly, but in the receiver side, I could retrieve all information correctly, except for the somePort info in the struct controlMsg_payload.
Below is my code in the receiver side
char* buf = malloc(sizeof(struct controlMessage));
data = recvfrom(sockfd,buf,sizeof(struct controlMessage), 0, struct (sockaddr*) &serv_addr, &serv_len);
struct iphdr* ip_hdr;
struct ipPayload* ip_payload;
ip_hdr = (struct iphdr*) buf;
ip_payload = (struct ipPayload*) (buf+sizeof(struct iphdr));
//from here I can print mType and cid correctly from ip_payload and also src & dest IP addr from ip_hdr
//The only information I did not get correctly is the somePort info below
struct controlMsg_payload* rcv_load;
rcv_load = (struct controlMsg_payload*) ip_payload->payload; //get this from the struct ipPayload and cast it as it is char* type, not sure if I did it right
printf ("my port = %d\n",rcv_load->somePort); //WRONG, not = 1000
I'm sorry for a lot of codes since it's hard to explain without it. Basically, I don't read somePort = 1000 back in the receiver side.
I tried the same last three lines (in the receiver side) in the sender side for testing purposes, I'm able to read back 1000. So I believe that it has to be the way I package the data and send/receive it over the network that causes this.
Could you guys please help me take a look? Thanks in advance!