在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
函數將接收到的數據存儲在這個緩沖區中。注意,你需要根據實際需求調整緩沖區的大小。如果預期接收的數據較大,可以增加緩沖區的大小以避免數據丟失。