getsockname
似乎总是用{family}设置为0的结构填充storage
,这表示未指定协议。
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;
}
}
在连接之后和关闭之前调用此函数。
用法示例:https://gist.github.com/Hajto/09058b335b2466033f96a9a1adfebef4 client.cpp:调用上面片段的代码,该片段应该获取有关连接到套接字的主机的信息 server.cpp:由于使用了该代码,因此在客户端中使用了该代码,我还附加了服务器以启用运行该客户端。