阅读量:0
在C++中,recvfrom
函数用于从一个套接字接收数据
#include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <cstring> #include<iostream> int main() { int sockfd; struct sockaddr_in server_addr, client_addr; socklen_t client_addr_size; char buffer[1024]; // 定义接收缓冲区大小 sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { std::cerr << "Error creating socket"<< std::endl; return 1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(8080); if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { std::cerr << "Error binding socket"<< std::endl; return 1; } client_addr_size = sizeof(client_addr); ssize_t recv_len = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &client_addr_size); if (recv_len < 0) { std::cerr << "Error receiving data"<< std::endl; return 1; } std::cout << "Received data: "<< buffer<< std::endl; close(sockfd); return 0; }
在这个示例中,我们定义了一个大小为1024字节的接收缓冲区。recvfrom
函数将接收到的数据存储在这个缓冲区中。注意,你需要根据实际需求调整缓冲区的大小。如果预期接收的数据较大,可以增加缓冲区的大小以避免数据丢失。