receiving reversed data in c socket programming

3

I want to write a c program that listen to a socket and get payload for a specific TCP protocol and send response. I have a problem in assigning value to response packet fields.

At first i created the protocol packet structures :

struct header {
    unsigned int field_1:32;
    unsigned int field_2:32;
    unsigned int field_3:32;
    unsigned int field_4:32;
}

struct request {
    struct header req_hdr;
    char req_body[100];
}


struct response {
    struct header resp_hdr;
    char resp_body[16];
}

After the server socket receives a request, it send a response to client. To do that i first create a response structure :

struct  response *resp;
resp = calloc (1, sizeof (struct response));

Then i fill response packet fields with appropriate value. resp->header.field_1 must be the length of the body PDU. I assign it in this way :

resp->header.field_1=strlen(resp->resp_body); 

And there is an hexadecimal value that must be assign to resp->header.field_2. i convert this hexadecimal number to integer and then assign it to resp->header.field_2. because in the protocol document resp->header.field_2 must be an integer and not a string. the equivalent integer of 0x80000009 is 2147483657, so i assign it in this way and send it to client:

resp->header.field_1=2147483657;

I used tshark on client system to check the response that the server are sending back. i get the packet like this :

04000000 09000080 00000000 00000001 74657374000000000000000000000000

First left byte is resp->header.field_1 and second is resp->header.field_2. here is the problem : resp->header.field_1 must be 00000004 and resp->header.field_2 must be 80000009 but it seems they are reversed (rest fields are ok) and it's caused the response packet can not be recognized by the client. how can i assign these value to the their fields correctly ?

c
sockets
asked on Stack Overflow Nov 25, 2019 by f_y

1 Answer

3

In your Server program you need to convert response header integers to from host byte stream to network order. You should use htons() or htonl() on it first. If you're receiving an integer in clinet, you should use ntohs() or ntohl().

answered on Stack Overflow Nov 25, 2019 by Sunil Bojanapally

User contributions licensed under CC BY-SA 3.0