只是想知道我是否有一个结构in_addr,如何将其转换回主机名?
You can use getnameinfo()
by wrapping your struct in_addr
in a struct sockaddr_in
:
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
. 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. For example, to lookup a hostname or text-form ip address:
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:
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
. Here you should use sockaddr_storage
unless you know the address family a priori.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.