协议不支持 C++ 地址系列

c++ address family not supported by protocol

本文关键字:系列 地址 C++ 不支持 协议      更新时间:2023-10-16

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

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( 返回"协议不支持的地址系列"。我不知道为什么会发生这种情况,因为在其他示例中,AF_INET很好地处理了IPPROTO_TCP

您需要

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