【问题标题】:c++ address family not supported by protocol协议不支持的c++地址族
【发布时间】:2018-09-19 07:12:37
【问题描述】:

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

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 一起使用

【问题讨论】:

    标签: c++ sockets networking tcp


    【解决方案1】:

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

    【讨论】:

    • 谢谢!这是一个非常愚蠢的问题。我刚刚用过:memcpy(&_sockaddr_in.sin_addr, _hostent->h_addr, _hostent->h_length);
    • 你真的不应该使用gethostbyname(),因为它已被弃用。改用getaddrinfo(),让它为你返回一个完全格式化的sockaddr_in
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多