2

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the client is taking a command that the server will execute so I should be able to just make that string in the client pass it over and not have to mess with it again Ill give this a try thanks for the quick reply!
2

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.

1 Comment

To clarify: in some instances you may be able to send arrays. If you know the size of the elements, for example byte[] should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.