发送和接收int C++

Bec*_*ker 4 c++ sockets int

如何向服务器发送4个字节int,在服务器端将此缓冲区转换为int.

客户端:

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);
}
Run Code Online (Sandbox Code Playgroud)

服务器端:

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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 10

您可以简单地把地址你的intchar*并把它传递到send/ recv.注意使用htonlntohl处理字节序.

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);
}
Run Code Online (Sandbox Code Playgroud)

注意:我保留了缺乏结果检查.实际上,您需要额外的代码来确保send和recv都传输所有必需的字节.