Convert struct in_addr to text

just wondering if I have an in_addr structure, how do I convert this back to hostname?

+3
source share
2 answers

You can use getnameinfo()by wrapping struct in_addrin 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);
}
+6
source

Modern code should not use struct in_addrdirectly, but rather sockaddr_in. It would be even better to never create or not create any structures at all sockaddr, but to do everything through library calls getaddrinfoand getnameinfo. For example, to search for a host IP address or text form:

struct addrinfo *ai;
if (getaddrinfo("8.8.8.8", 0, 0, &ai)) < 0) goto error;

And to get the name (or the address of the ip-form of the text form, if it does not cancel, resolve) the address:

if (getnameinfo(ai.ai_addr, ai.ai_addrlen, buf, sizeof buf, 0, 0, 0) < 0) goto error;

, , sockaddr, getpeername getsockname recvfrom. sockaddr_storage, .

:

  • , ( ip ..) .
  • IPv6 (, , , IPv4).
  • gethostbyname gethostbyaddr POSIX, //.
+4
source

Source: https://habr.com/ru/post/1776998/


All Articles