c++

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

小亿
808
2024-02-29 09:30:24
栏目: 编程语言

在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发送和接收示例,可以根据实际需求进行进一步的扩展和优化。

0
看了该问题的人还看了