linux - Server-client in C: Weird behaviour when sending bytes -
i'm trying write server-client program in c wherein client send bunch of messages in form of 5 bytes: first byte contain command, , next 4 contain key. looks this:
rc = write(sockfd, &op, 1); if (rc != 1) { printf("error! write() failed: %s\n", strerror(errno)); break; } 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; }
on receiving end, have:
while((bytes = recv(socket,buffer,5,0)) > 0) { //printf("%d\t%d\t%d\t%d\t%d\n",(int)buffer[0],(int)buffer[1], (int)buffer[2],(int)buffer[3],(int)buffer[4]); key = ((buffer[4] << 24) | (buffer[3] << 16) | (buffer[2] << 8) | (buffer[1])); if((int)buffer[0] == 0) { command 0, etc...
the problem i'm having cant key. i've tried switching order of shifts, i'm getting numbers don't match keys client sending. i'm @ loss.
even stranger, if compile server without print under while, seg-faulted. if uncomment printf, works fine. seems super strange.
does know might causing this? in advance.
rc = write(sockfd, &net_num + nsent, 4 - nsent);
wrong, &net_num
pointer 32 bits object, &net_num+1
point next 32bits object. beyond object. cast char pointer, or copy small char buffer before sending, below:
uint32_t net_num = htonl(num); char buff[sizeof net_num]; memcpy (buff, &net_num, sizeof buff); int nsent; nsent=0; nsent < sizeof buff; nsent += rc;) { rc = write(sockfd, buff + nsent, 4 - nsent); if (rc == -1 && errno == eagain) { rc=0; continue; } if (rc <= 0) { printf("error! write() failed: %s\n", strerror(errno)); break; } }
Comments
Post a Comment