Skip to content

Instantly share code, notes, and snippets.

@jkomyno
Last active August 29, 2024 18:43
Show Gist options
  • Save jkomyno/45bee6e79451453c7bbdc22d033a282e to your computer and use it in GitHub Desktop.
Save jkomyno/45bee6e79451453c7bbdc22d033a282e to your computer and use it in GitHub Desktop.
Convert a struct sockaddr address to a string, IPv4 and IPv6
// Convert a struct sockaddr address to a string, IPv4 and IPv6:
char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
switch(sa->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
s, maxlen);
break;
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
s, maxlen);
break;
default:
strncpy(s, "Unknown AF", maxlen);
return NULL;
}
return s;
}
@DiaoWang
Copy link

Thank you so much !

@Tachi107
Copy link

Or, even better, just call getnameinfo()

char name[INET6_ADDRSTRLEN];
char port[10];
getnameinfo(sa, sizeof(sa), name, sizeof(name), port, sizeof(port), NI_NUMERICHOST | NI_NUMERICSERV);
printf("%s:%s\n", name, port);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment