简体   繁体   English

如何获得套接字的稳定主机名?

[英]How to get a stable hostname of a socket?

With an open socket accepted by a listen socket I want to get the hostname of the remote end. 在侦听套接字接受开放套接字的情况下,我想获取远程端的主机名。 Using getnameinfo() for hosts that have multiple hostnames I don't always get the same hostname. 对于具有多个主机名的主机使用getnameinfo(),我并不总是获得相同的主机名。 Is it possible to get all of them or at least get the same one each time? 是否可以全部获得或至少每次都获得相同的?

I've read in some docs something about a canonical hostname but can't find more information beyond a suggesting that this is what I need. 我已经在一些文档中阅读了有关规范主机名的信息,但是除了暗示这就是我所需要的信息之外,找不到其他信息。

Here's how I call getnameinfo() 这就是我所谓的getnameinfo()

char szHostname[ NI_MAXHOST ];
const sockaddr* pSock;
int nSockLen;

// stuff to get a pSock

int ret = getnameinfo( pSock, nSockLen, szHostname, NI_MAXHOST, 0, 0, NI_NAMEREQD );
if ( ret != 0 )
    ret = getnameinfo( pSock, nSockLen, szHostname, NI_MAXHOST, 0, 0, NI_NUMERICHOST );

printf( szHostname );

If a peer X has multiple hostnames AAA & BBB szHostname could have either. 如果对等X具有多个主机名,则AAA和BBB szHostname可以具有两个。

Use gethostbyaddr() , it will gives you all DNS entries for your internet address (IPv4 only). 使用gethostbyaddr() ,它将为您的互联网地址(仅IPv4)提供所有DNS条目。 The first one should be the canonical one. 第一个应该是规范的。 If you need IPv6, then (if think that) you should use getaddrinfo() and set the AI_CANONNAME in the hints (see manual). 如果需要IPv6,则(如果认为如此)应使用getaddrinfo()并在提示中设置AI_CANONNAME(请参见手册)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM