2

How do you pass a structure from the UDP client to the UDP server in C using sockets? How can you access the variables that structure contains on the server? If the structure below is transmitted, how does the server see what the name or age is?

struct animal { int age; char name[25]; }; 
1
  • You send it like usual (if both the server and client have the same rules regarding endianess and structure padding). What have you tried? How did that work, or not work? Commented Feb 28, 2015 at 18:56

2 Answers 2

1

The Right Answer, which will protect you from differences in endianness, integer size, and future changes of the structure across server and client versions, is to use something like Google Protobuf. This is a library which will pack your structure members into a neutral packet format which can then be parsed on the other side.

However, for someone learning about low-level UDP sockets, sending a structure like that between two identical machines is simple:

send( sock, &myanimal, sizeof( myanimal ), 0 ); 

and on the server:

recv( sock, &newanimal, sizeof( myanimal ), 0 ); 

(Use sendto and recvfrom for unconnected UDP sockets).

That will make a byte-for-byte copy which works just like memcpy() across the wire. If your hosts don't match closely, that copy might not line up with your structure. But if they do, you will access it on the server just like you did on the client.

You can use socketpair() to make both ends of a socket in your own process (much like pipe()) and test this without even constructing the UDP part. Once it works there, move on to UDP.

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

1 Comment

Alright, thanks. That really clears up some of the doubts I had when initially writing this. I thought, for the most part, this was they way it went from looking at various things on the internet but I wanted to get the opinion of the pros. Thanks again.
1

What you write to the UDP packet buffer is the content of the structure starting at the address of the structure. The receiving end should copy the received data into a buffer of the same size, then cast it to the exact same struct, defined the exact same way.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.