[英]convert struct in_addr to text
只是想知道我是否有一个结构in_addr,如何将其转换回主机名?
You can use getnameinfo()
by wrapping your struct in_addr
in a struct sockaddr_in
: 您可以通过将
struct in_addr
包装在struct sockaddr_in
来使用getnameinfo()
:
int get_host(struct in_addr addr, char *host, size_t hostlen)
{
struct sockaddr_in sa = { .sin_family = AF_INET, .sin_addr = my_in_addr };
return getnameinfo(&sa, sizeof sa, host, hostlen, 0, 0, 0);
}
Modern code should not use struct in_addr
directly, but rather sockaddr_in
. 现代代码不应该直接使用
struct in_addr
,而应该使用sockaddr_in
。 Even better would be to never directly create or access any kind of sockaddr
structures at all, and do everything through the getaddrinfo
and getnameinfo
library calls. 更好的方法是永远不要直接创建或访问任何类型的
sockaddr
结构,并通过getaddrinfo
和getnameinfo
库调用来完成所有工作。 For example, to lookup a hostname or text-form ip address: 例如,要查找主机名或文本格式的ip地址:
struct addrinfo *ai;
if (getaddrinfo("8.8.8.8", 0, 0, &ai)) < 0) goto error;
And to get the name (or text-form ip address if it does not reverse-resolve) of an address: 并获取地址的名称(或文本形式的IP地址,如果它不反向解析):
if (getnameinfo(ai.ai_addr, ai.ai_addrlen, buf, sizeof buf, 0, 0, 0) < 0) goto error;
The only other time I can think of when you might need any sockaddr
type structures is when using getpeername
or getsockname
on a socket, or recvfrom
. 我可以想到你可能需要任何
sockaddr
类型结构的唯一另一个时间是在套接字上使用getpeername
或getsockname
,或者recvfrom
。 Here you should use sockaddr_storage
unless you know the address family a priori. 除非您事先了解地址族,否则应使用
sockaddr_storage
。
I give this advice for 3 reasons: 我提出这个建议有三个原因:
gethostbyname
and gethostbyaddr
were actually removed from the latest version of POSIX because they were considered so obsolete/deprecated/broken. gethostbyname
和gethostbyaddr
实际上已从最新版本的POSIX中删除,因为它们被认为是过时/弃用/损坏的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.