C++怎么实现udp发送和接收

avatar
作者
筋斗云
阅读量:0

在C++中实现UDP发送和接收可以使用socket编程。下面是一个简单的示例代码:

发送UDP数据包:

#include <iostream> #include <string> #include <cstring> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h>  int main() {     int sockfd;     struct sockaddr_in serverAddr;      // 创建UDP socket     sockfd = socket(AF_INET, SOCK_DGRAM, 0);     if (sockfd < 0) {         std::cerr << "Failed to create socket" << std::endl;         return -1;     }      // 设置服务器地址和端口     serverAddr.sin_family = AF_INET;     serverAddr.sin_port = htons(12345);     serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");      // 发送数据     std::string message = "Hello, UDP!";     sendto(sockfd, message.c_str(), message.length(), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));      close(sockfd);      return 0; } 

接收UDP数据包:

#include <iostream> #include <string> #include <cstring> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h>  int main() {     int sockfd;     struct sockaddr_in serverAddr, clientAddr;     socklen_t addrLen = sizeof(clientAddr);     char buffer[1024];      // 创建UDP socket     sockfd = socket(AF_INET, SOCK_DGRAM, 0);     if (sockfd < 0) {         std::cerr << "Failed to create socket" << std::endl;         return -1;     }      // 设置服务器地址和端口     serverAddr.sin_family = AF_INET;     serverAddr.sin_port = htons(12345);     serverAddr.sin_addr.s_addr = INADDR_ANY;      // 绑定地址和端口     bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));      // 接收数据     int bytesReceived = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr*)&clientAddr, &addrLen);     buffer[bytesReceived] = '\0';      std::cout << "Received: " << buffer << std::endl;      close(sockfd);      return 0; } 

以上代码实现了一个简单的UDP发送和接收示例,可以根据实际需求进行进一步的扩展和优化。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!