将 std::string 作为参数传递会给出错误 - htons 函数

Passing std::string as parameter gives error - htons function

本文关键字:错误 出错 htons 函数 参数传递 string std      更新时间:2023-10-16

我正在使用套接字,但是当我编译程序时,我遇到了一些错误。

这是我的代码:

address.sin_family = AF_INET;
address.sin_port = htons(string); // here I get an error
inet_aton(str.c_str(),&address.sin_addr);

我得到的是:

无法将参数"1"的"__gnu_cxx::__alloc_traits>>::value_type {aka std::__cxx11:basic_string}"转换为"uint16_t {aka short unsigned int}",参数"1"转换为"uint16_t htons(uint16_t(">

如何解决此错误?

提前谢谢。

您需要将

std::string转换为std::uint16_t。 我推荐一个stringstream

std::istringstream ss(string); // maybe pick a different name
std::uint16_t port{};
ss >> port;
address.sin_port = htons(port);

请务必#include <sstream>

htons 需要uint16_t
这意味着您必须将端口作为整数传递,而不是字符串

相关文章: