I have a simple TCP connection with a server and a client program.
I made a simple struct in both the server and the client to pass as the message:
struct {int c; char** v;} msg;
I am just trying to send the argc and argv (input from terminal) from the client:
int main(int argc, char **argv){
...
msg.c = argc;
msg.v = argv;
sendto(Socket, &msg, sizeof(msg), 0, (struct sockaddr *)&input, sizeof(input));
but when sent to the server I can call msg.c to get the number and I can use that
but if I try to use the array of strings I get a seg fault:
recvfrom(Socket, &msg, sizeof(msg), 0, (struct sockaddr *)&input, &sizep);
printf("%d\n", msg.c);
printf("%s\n", msg.v[2]);
I have tried this with just one char * and I wasn’t able to send the string across either.
What am I doing wrong?
The
sendto()function doesn’t follow pointers, at all. So you’re sending your message which consists of an integer, and one pointer, to the other side. The receiver gets a pointer value that points to some random place in memory that doesn’t mean anything.What you need to do is serialize your data into something that can be sent across a socket. That means, no pointers. For example, for a single string you could send the length, followed by the actual bytes of the string. For multiple strings, you could send a count, followed by a number of strings in the same format as a single string.
Once you receive the data you will need to unserialize the data into an array of
char *strings, if that’s what you need in the receiver.