gpt4 book ai didi

协议(protocol)不支持的 C++ 地址族

转载 作者:可可西里 更新时间:2023-11-01 02:50:18 25 4
gpt4 key购买 nike

我写了一个方法,它创建一个套接字,将它连接到端点,然后返回它的描述符:

static int open_socket(const char* host, unsigned short port)
{
#ifdef USE_IPV4
struct hostent* _hostent;
struct sockaddr_in _sockaddr_in;

// Variables
size_t sockaddr_len;
int sock_family;
int sock_type;
int sock_protocol;
int sockfd;

_hostent = gethostbyname(host);
if (_hostent == (struct hostent*) 0)
{
// Not Found
}

_sockaddr_in.sin_family = AF_INET;
sock_family = AF_INET;
sock_type = SOCK_STREAM;
sock_protocol = IPPROTO_TCP;
sockaddr_len = sizeof(_sockaddr_in);
(void*) memmove(&_sockaddr_in, _hostent->h_addr, _hostent->h_length);
_sockaddr_in.sin_port = htons(port);

// Now create socket
sockfd = socket(sock_family, sock_type, sock_protocol);
if (sockfd < 0)
{
// "Internal Error"
}
if (connect(sockfd, (struct sockaddr*) &_sockaddr_in, sockaddr_len) < 0)
{
std::cerr << strerror(errno) << std::endl;
std::cerr << "Endpoint is unavailable" << std::endl;
return 0;
// "Unavailable"
}

return sockfd;

#endif
}

当我尝试连接套接字时发生错误。 strerror(errno) 返回“协议(protocol)不支持的地址族”。我不明白为什么会这样,因为在其他示例中,AF_INET 可以很好地与 IPPROTO_TCP 配合使用

最佳答案

您需要将地址存储在 sockaddr_in::sin_addr 中。当您调用 memmove(&_sockaddr_in, ...) 时,您将覆盖整个结构(从 sin_family 开始)。

关于协议(protocol)不支持的 C++ 地址族,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com