Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send and receive int C++

Tags:

c++

int

sockets

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;
}
like image 687
Becker Avatar asked Dec 16 '22 23:12

Becker


2 Answers

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.

like image 152
Robᵩ Avatar answered Jan 03 '23 00:01

Robᵩ


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.

like image 42
Nikolai Fetissov Avatar answered Jan 03 '23 01:01

Nikolai Fetissov