c++ - 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);
}
解决方案
推荐阅读
- javascript - 在 d3v4 中将长数据转换为宽数据的更新函数
- java - Java MQQueueConnection 获取客户端和服务器版本
- java - TableView 项目不刷新,但被正确添加,从不同的控制器添加它们后
- tooltip - 如何根据消息长度调整工具提示气泡大小?
- excel - 当指向不存在的内部工作表的公式是有目的的时,如何防止 Excel“我们无法更新链接”对话框?
- react-native - 如何从 RNPickerSelect 制作 SearchableDropdown?
- reactjs - 在 useEffect 中使用 setter 和 setInterval 时状态不更新
- indexing - 在 Xpress Mosel 中的集合中索引变量
- cython - 对 Cython 类型的一流支持
- firebase - Firesbase 存储安全规则允许不遵循更新规则