Last active
August 29, 2024 18:43
-
-
Save jkomyno/45bee6e79451453c7bbdc22d033a282e to your computer and use it in GitHub Desktop.
Convert a struct sockaddr address to a string, IPv4 and IPv6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
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
Thank you so much !