you can declare a structure to hold the things you need to send....
struct _stuff {
int int_one;
int int_two;
char ascii[4]; // or [3] if you don't want to send a terminating
null]
} s;
then, one complication as you're filling in the structure has to do
with big-endian vs. little-endian computers, i.e. if you're sending
your data from a macintosh to an intel computer. you use the
functions htonl() and ntohl(), read as "host to network long" and
"network to host long" to convert to the "standard" format for the
network. (further discussion at
http://telecom.vub.ac.be/sockprog/endian.htm, if you're interested.)
so, to send your data....
s.int_one = htonl(int_one);
s.int_two = htonl(int_two);
s.ascii[0] = first_char;
s.ascii[1] = second_char;
s.ascii[2] = third_char;
s.ascii[3] = '\0'; // null terminate the string, if you want....
send(sock, (char *) &s, sizeof(s));
and when you're receiving, it's pretty similar....
recv(sock, (char *) &s, sizeof(s), flags);
int_one = ntohl(s.int_one);
int_two = ntohl(s.int_two);
assuming that you've done the null-terminated version of the
structure, the characters in the structure make a perfectly good
string.... so you could just write
char my_string[4];
strcpy(my_string, s.ascii);
but this wouldn't really be a good idea, because then if the data
you're receiving *didn't* happen to have a zero in the last byte of
s.ascii[3], you'd run off the end of your structure and something
random would happen. (important rule of network programming: never
trust any data you get over the network!)
so it might be better to at least check that the string was properly
null-terminated, or at least to use a length-limited routine like
strncpy(my_string, s.ascii, 4);
I hope this explanation makes sense; if you have further questions,
feel free to ask for a clarification....
Thanks,
David |