How to send to server 4 bytes int
and on server side conver this buffer to int.
client side:
void send_my_id()
{
int my_id = 1233;
char data_to_send[4];
// how to convert my_id to data_send?
send(sock, (const char*)data_to_send, 4, 0);
}
server side:
void receive_id()
{
int client_id;
char buffer[4];
recv(client_sock, buffer, 4, 0);
// how to conver buffer to client_id? it must be 1233;
}
You may simply cast the address of your int
to char*
and pass it to send
/recv
. Note the use of htonl
and ntohl
to deal with endianness.
void send_my_id()
{
int my_id = 1233;
int my_net_id = htonl(my_id);
send(sock, (const char*)&my_net_id, 4, 0);
}
void receive_id()
{
int my_net_id;
int client_id;
recv(client_sock, &my_net_id, 4, 0);
client_id = ntohl(my_net_id);
}
Note: I preserved the lack of result-checking. In reality, you'll need extra code to ensure that both send and recv transfer all of the required bytes.
The usual convention since the beginning of the internet was to send binary integers in Network Byte Order (read big-endian). You can use htonl(3)
and friends to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With