convert struct in_addr to text
just wondering if I ha开发者_StackOverflow中文版ve a struct in_addr, how do I convert that back to a host name?
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:
- It's a lot easier doing all of your string-to-address-and-back conversion with these two functions than writing all the cases (to handle lookup failures and trying to parse the address as an ip, etc.) separately.
- Coding this way makes it trivial to support IPv6 (and potentially other non-IPv4) protocols.
- The old functions
gethostbyname
andgethostbyaddr
were actually removed from the latest version of POSIX because they were considered so obsolete/deprecated/broken.
精彩评论