I’m quite new to C and am having trouble with writing to streams using sockets.
I’m using a network stream/socket to try to send messages in two directions (from host to client and client to host) however when I get the message back from the client it’s scrambled (due to an encoding issue I guess?).
Here’s the relevant parts of my code:
host.c
int client_sock_fd;
int main(int argc, const char* argv[]) {
while (1) {
char input[80];
scanf("%s", input);
// send to client, transmitted fine
write(client_sock_fd, &input, sizeof(input));
char response[80];
read(client_sock_fd, &response, sizeof(response));
// Prints the missing character symbol, and 'random' letters
printf("Response: %s\n", response);
}
}
client.c
int host_sock_fd; // file descriptor for host
void writeResponse(
int main(int argc, const char* argv[]) {
while (1) {
char message[80];
// the message is transmitted fine
read(host_sock_fd, &message, sizeof(message));
writeResponse("Response message");
}
}
void writeResponse(char response[80]) {
write(host_sock_fd, &response, sizeof(response));
}
I’m not really sure how to continue. I know if I simply write back the received message in client it works fine, so is this a problem with the amount of memory for each char?
I showed a lack of knowledge below, and I’m not going to delete it, but this is what causeing your problem in
writeResponse(char response[80])sinceresponseis treated aschar *and notchar[80]. But in general, don’t use the&when it is not needed, it causes mistakes just as the one you had. treatchar[]aschar *where it is about the level of referencing, there are differences between those two, but not in this case.It’s weird that it works at all, since you declared your buffers aschar input[80];etc., those variables are already char pointers and you should not pass their address as parameter to the read /write functions so it should be:instead of:
in all cases of read write. You may want to take a look at those examples