如boost文档中所述:
ip::basic_endpoint::port (1 of 2 overloads)
unsigned short port() const;
此getter获取与端点关联的端口。端口号始终以主机的字节顺序排列。
我知道Little-endian字节排序首先放置最低有效字节。但是,Big-endian字节排序首先放置最重要的字节。
在C语言中,我们使用这些函数:
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
如何在boost asio中获取正确的端口号?
谢谢
https://www.boost.org/doc/libs/1_69_0/doc/html/boost_asio/reference/ip__basic_endpoint/port.html
此getter获取与端点关联的端口。端口号始终以主机的字节顺序排列。
因此,由于您在该主机上调用该函数,因此只需调用该函数即可返回正确的端口。
我想这个“奇怪”的评论是在图书馆的作者实现某些协议的低层/思考原始套接字时发生的。如果要实现特定协议,只需要警告您需要转换为网络字节顺序。这使得评论在basic_endpoint
提供的抽象层次上几乎完全是多余的,但是谁知道这可能是某些人在实现(专业化)时忘记了。
问题是UDP是无连接协议。因此,remote_endpoint在发送数据后保存垃圾。
代码证明了这一点
boost::system::error_code ec;
boost::asio::ip::udp::endpoint endpoint = socket.remote_endpoint(ec);
if(ec)
{
std::cout << "An error occurred." << '\n';
std::cout << ec.value() << " " << ec.message() << '\n';
return;
}
输出:
发生错误。 107未连接传输端点