在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發送和接收示例,可以根據實際需求進行進一步的擴展和優化。