Rather not do this yourself, use libraries which do this for you, like Boost.Asio and Boost.Serialization.
Boost Asio is a library which replaces sockets and even provides an interface like C++ iostreams and will handle sending/recieving builtin types like int
for you.
Boost Serialization enables you to easily serialize your classes so you can send them over the network.
IF you cant use additional libraries, you will have to send the data manually over plain sockets - make sure you dont forget to use htons
, ntohs
, htonl
and ntohl
functions, or your code will break when the two communicating computers use different endianess (byte order).
small snippet:
// sender:
unsigned long to_send = 123;
unsigned long to_send_n = htonl(to_send); // convert to network byte order
send(send_socket, (const char*)(&to_send_n), sizeof(unsigned long), flags);
// reciever:
char recv_buf[sizeof(unsigned long)];
recv(recv_socket, recv_buf, sizeof(unsigned long)); //recieve number
unsigned long recieved = ntohl(*((unsigned long*)recv_buf), flags); // convert back to host byte order
Since these functions only exist for unsigned types, you will be limited to unsigned types..