Mintybacon
Mintybacon

Reputation: 331

Passing an array of strings through a socket

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?

Upvotes: 2

Views: 3368

Answers (2)

Mene
Mene

Reputation: 3799

You cannot send an Array. What you seem to do is to send a pointer to an array. The pointer is a value that points to the beginning of the array in the sender's RAM. However this address is local to one client. If you need to send complex data like an array or classes / structs you usually need to serialize them. There are libraries around to support you. I used Google's Protocol Buffers and liked it; you may want to take a look at it.

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 993223

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.

Upvotes: 4

Related Questions