getsockname always return structure with protocol

2019-08-27 03:07发布

问题:

getsockname always seem to fill storage with a structure that has family set to zero which implies that protocol is unspecified.

void print_address_attached_to_socket(int socket) {
    socklen_t socket_length;
    struct sockaddr_storage storage;
    int returncode = getsockname(socket, (struct sockaddr *) (&storage), &socket_length);
    if (returncode != 0) {
        perror("Errror getting sock name");
        exit(1);
    }
    if (storage.ss_family == 0) {
        std::cout << "Family is unspecified getsockname failed without telling why..." << std::endl;
        return;
    } else {
        struct sockaddr *sock_addr = (struct sockaddr *) &storage;
        char host[128] = {0}, serv[128] = {0};
        returncode = getnameinfo(sock_addr, socket_length, host, 128, serv, 128, NI_NUMERICHOST | NI_NUMERICSERV);
        if (returncode != 0) {
            printf("Errror getting resolving name");
            exit(1);
        }
        std::cout << "Host: " << host << ":" << std::endl;
    }
}

This function is called after connect and before close.

Example usage: https://gist.github.com/Hajto/09058b335b2466033f96a9a1adfebef4 client.cpp: Code that calls above fragment that supposed get info about host connected to socket server.cpp: since the code is used the code is used in client I also attached server to enable running the client.