首页 > 解决方案 > boost asio 无法设置 UDP 源端口

问题描述

我用 C++ 编写了一个带有 boost asio 的 UDP 类。目前,当我发送 UDP 数据时,会选择一个随机源端口。目的端口和 ip 地址在端点创建时传入。如何将源端口设置为在端口 8410 上发送?代码如下:

UDPClient.h

#pragma once
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>

class UDPClient {
public:
    UDPClient(const std::string& ipAddress, const std::string& port);
    ~UDPClient();

    void Send(unsigned char* buff, int size);

private:
    boost::asio::io_service ioService;
    boost::asio::ip::udp::socket socket;
    boost::asio::ip::udp::endpoint remoteEndpoint;
};

UDPClient.cpp

#include "UDPClient.h"

UDPClient::UDPClient(const std::string& ipAddress, const std::string& port) : socket{ ioService } {
    socket.open(boost::asio::ip::udp::v4());

    boost::asio::socket_base::broadcast option(true);
    socket.set_option(option);

    this->remoteEndpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(ipAddress), boost::lexical_cast<int>(port));
}

UDPClient::~UDPClient() {
    socket.close();
}

void UDPClient::Send(unsigned char* buff, int size) {
    const std::string stringBuffer(reinterpret_cast<const char*>(buff), size);
    socket.send_to(boost::asio::buffer(stringBuffer, size), this->remoteEndpoint);
}

标签: c++socketsboostudpboost-asio

解决方案


推荐阅读