-const char *get_ip_addr(const char *interface) {
- static char part[512];
- socklen_t len = sizeof(struct sockaddr_in);
- memset(part, 0, sizeof(part));
-
- struct ifaddrs *ifaddr, *addrp;
- bool found = false;
-
- getifaddrs(&ifaddr);
-
- if (ifaddr == NULL)
- return NULL;
-
- /* Skip until we are at the AF_INET address of interface */
- for (addrp = ifaddr;
-
- (addrp != NULL &&
- (strcmp(addrp->ifa_name, interface) != 0 ||
- addrp->ifa_addr == NULL ||
- addrp->ifa_addr->sa_family != AF_INET));
-
- addrp = addrp->ifa_next) {
- /* Check if the interface is down */
- if (strcmp(addrp->ifa_name, interface) != 0)
- continue;
- found = true;
- if ((addrp->ifa_flags & IFF_RUNNING) == 0) {
- freeifaddrs(ifaddr);
- return NULL;
- }
+const char *get_ip_addr(const char *interface, int family) {
+ static char part[512];
+ socklen_t len = 0;
+ if (family == AF_INET)
+ len = sizeof(struct sockaddr_in);
+ else if (family == AF_INET6)
+ len = sizeof(struct sockaddr_in6);
+
+ memset(part, 0, sizeof(part));
+
+ struct ifaddrs *ifaddr, *addrp;
+ bool found = false;
+
+ getifaddrs(&ifaddr);
+
+ if (ifaddr == NULL)
+ return NULL;
+
+ /* Skip until we are at the input family address of interface */
+ for (addrp = ifaddr; addrp != NULL; addrp = addrp->ifa_next) {
+ /* Strip the label if present in the .ifa_name field. */
+ char *stripped_ifa_name = strip_optional_label(addrp->ifa_name);
+
+ bool name_matches = strcmp(stripped_ifa_name, interface) != 0;
+ free(stripped_ifa_name);
+ if (name_matches) {
+ /* The interface does not have the right name, skip it. */
+ continue;