ubuntu - C: Weird behaviour between client and server -


i'm writing server-client program in c. client sends command server in form of 5 bytes: first byte operation, , next 4 bytes key operation on.

the server looks this:

int nowread, key; while(1) {     char buffer[1024];     int alreadyread = 0;         {         nowread = read(socket,buffer+alreadyread,5-alreadyread);         alreadyread += nowread;     }     while((nowread > 0) && (5-alreadyread > 0));      if(nowread == -1 || nowread == 0)     {         printf("error reading client socket\n");         exit(1);     }      key = (((int)buffer[1])<<24 | ((int)buffer[2])<< 16 | ((int)buffer[3]) << 8 | ((int)buffer[4]) << 0);      printf("%d, key server \n",key); // debugging   //do command 

i've been testing program having client send 10 commands:

 op: 1, num: 645110  op: 2, num: 419811  op: 0, num: 115300  op: 2, num: 792023  op: 2, num: 146624  op: 1, num: 842346  op: 1, num: 450778  op: 0, num: 550046  op: 1, num: 284186  op: 2, num: 691858 

and server:

-10, key server  -29, key server  -15772, key server  -41, key server  -64, key server  -9622, key server  -38, key server  -98, key server  284186, key server  -110, key server  

as can see, 1 key matches, strange (either should match or none). 100% sure serverside , not problem client. know causing this?

thanks in advance.

edit: code sends data

    uint32_t net_num = htonl(num);     int nsent = 0;     while (nsent < 4)     {         rc = write(sockfd,&net_num + nsent, 4 - nsent);         if (rc <= 0)         {             printf("error! write() failed: %s\n", strerror(errno));             break;         }          nsent += rc;     }      if (rc <= 0)         break; 

you processing buffer in wrong direction. need convert network bytes. ntohl ( ) that.

like this:

uint32_t key; uint32_t result;  key = ( uint32_t )(( buffer [ 1 ] << 0 )  |                    ( buffer [ 2 ] << 8 )  |                    ( buffer [ 3 ] << 16 ) |                    ( buffer [ 4 ] << 24 ));  result = ntohl ( key ); 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -