Click here to Skip to main content
15,072,209 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a structure:
typedef struct{
    int flags;/*the type of message*/
    int length;/*the length of message*/
    void* message;/*the message*/

The length of message is variable.For example:
Message msg;
char buf[]="abcdef";

How can i send the structure from client to the server with socket? Someone help me!or give me some advisements.

1 solution

The binary representation of your data in memeory and its serialized binary form that you write into stream (for example to a filestream, or pipe stream, or into a network stream backed by sockets) are often different.
You are curious about the serialization of your variable length string and about its deserialization on the other side of the connection. Its simple:
First you send the length of the string to your socket (for example as an int32) then you send the string data itself. On the other side of the connection you read out the length into a variable, and then you know how long the string is and how many bytes to read into your string.
sum_and_sum 12-Aug-12 8:59am
but i saw the function: ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags);
the structure of msg like this:
<pre lang="c++">
struct msghdr {
void *msg_name; /* optional address */
socklen_t msg_namelen; /* size of address */
struct iovec *msg_iov; /* scatter/gather array */
size_t msg_iovlen; /* # elements in msg_iov */
void *msg_control; /* ancillary data, see below */
size_t msg_controllen; /* ancillary data buffer len */
int msg_flags; /* flags on received message */

struct iovec { /* Scatter/gather array items */
void *iov_base; /* Starting address */
size_t iov_len; /* Number of bytes to transfer */

the ivo_base is variable arrary.
sum_and_sum 12-Aug-12 9:00am
How to do like this function
pasztorpisti 12-Aug-12 9:06am
You question is unclear. Where does this function come from and what do you want to know?
sum_and_sum 12-Aug-12 9:10am
this function come from

in linux c
pasztorpisti 12-Aug-12 9:12am
OK, still I don't know what is your problem you can't solve. And why are you inspecting these structures in the linux headers?
sum_and_sum 12-Aug-12 9:15am
Now i solve the problem with you idea,thank you.
pasztorpisti 12-Aug-12 9:18am
You are welcome! Dont jump to more complex problems before solving the simpler ones. :-)
BTW, you can send variable length arrays that are inside other variable length arrays as well. The key is always sending some info first (the type of the thing, length of the array, etc...) so that the other side knows how to read the data that follows.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900